[英]Calculate the frequency for each word in text file, store it in a variable using python
但没有内置计数器功能的帮助
使用 open(r"C:\\Users\\muizv\\Desktop\\alice_in_wonderland.txt", "rt") 作为 f:
您可以读取文件的内容: content = f.read()
,然后使用正则表达式查找所有单词words = re.findall(r'[a-zA-Z]+', content)
然后遍历列表并使用字典来计算单词:
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1 # adds 1 to the freq of the current word, with 0 as the default
console.log(freq)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.