如果您需要计算段落中的单词数,则最好使用正则表达式。
让我们从一个简单的例子开始:
import remy_string = "Wow! Is this true? Really!?!? This is crazy!"words = re.findall(r'w+', my_string) #This finds words in the document
结果:
>>> words['Wow', 'Is', 'this', 'true', 'Really', 'This', 'is', 'crazy']
请注意,“是”和“是”是两个不同的词。我的猜测是,您希望对它们进行相同的计数,因此我们可以将所有单词大写,然后对其进行计数。
from collections import Countercap_words = [word.upper() for word in words] #capitalizes all the wordsword_counts = Counter(cap_words) #counts the number each time a word appears
结果:
>>> word_countsCounter({'THIS': 2, 'IS': 2, 'CRAZY': 1, 'WOW': 1, 'TRUE': 1, 'REALLY': 1})你准备好了吗?
现在,我们需要做的与上次完全相同,只是这次我们正在读取文件。
import refrom collections import Counterwith open('your_file.txt') as f: passage = f.read()words = re.findall(r'w+', passage)cap_words = [word.upper() for word in words]word_counts = Counter(cap_words)


