2 回答

TA贡献1772条经验 获得超8个赞
def word_count(fname, word_list):
count_w = dict()
for w in word_list:
count_w[w] = 0
with open(fname) as input_text:
text = input_text.read()
words = text.lower().split()
for word in words:
_word = word.strip('.,:-)()')
if _word in count_w:
count_w[_word] +=1
return count_w
def punctaction_count(fname, punctaction):
count_p = dict()
for p in punctaction:
count_p[p] = 0
with open(fname) as input_text:
for c in input_text.read():
if c in punctaction:
count_p[c] +=1
return count_p
print(word_count('c_prog.txt', ["also", "although", "and", "as", "because", "before", "but", "for", "if", "nor", "of", "or", "since", "that",
"though", "until", "when", "whenever", "whereas", "which", "while", "yet"]))
print(punctaction_count('c_prog.txt', [",", ";", "-", "'"]))
如果您想在一个功能中执行此操作:
def word_count(fname, word_list, punctaction):
count_w = dict()
for w in word_list:
count_w[w] = 0
count_p = dict()
for p in punctaction:
count_p[p] = 0
with open(fname) as input_text:
text = input_text.read()
words = text.lower().split()
for word in words:
_word = word.strip('.,:-)()')
if _word in count_w:
count_w[_word] +=1
for c in text:
if c in punctaction:
count_p[c] +=1
count_w.update(count_p)
return count_w
print(word_count('c_prog.txt', ["also", "although", "and", "as", "because", "before", "but", "for", "if", "nor", "of", "or", "since", "that",
"though", "until", "when", "whenever", "whereas", "which", "while", "yet"], [",", ";", "-", "'"]))

TA贡献1805条经验 获得超9个赞
在 2.7 和 3.1 中,您要实现的目标有特殊的Counter dict
由于您尚未发布任何示例输出。我想给你一个你可以使用的方法。维护一个列表。在列表中附加您需要的这些单词。例如,如果您接近单词“also”,请将其附加到列表中。
>>> l.append("also")
>>> l
['also']
同样,你遇到“虽然”这个词,列表变成:
>>> l.append("although")
>>> l
['also', 'although']
如果您再次遇到“也”,请再次将其附加到上面的列表中。
列表变为:
['also', 'although', 'also']
现在使用 Counter 来计算列表元素的出现次数:
>>> l = ['also', 'although', 'also']
>>> result = Counter(l)
>>> l
['also', 'although', 'also']
>>> result
Counter({'also': 2, 'although': 1})
添加回答
举报