Python按字长统计单词数
我得到了一个带有文本的 .txt 文件。我已经清理了文本(删除了标点符号、大写字母、符号),现在我有了一个包含单词的字符串。我现在试图获取len()字符串上每个项目的字符数。然后绘制一个图,其中 N 个字符在 X 轴上,Y 轴是具有这样 Nlen()个字符的单词数
到目前为止,我有:
text = "sample.txt"
def count_chars(txt):
result = 0
for char in txt:
result += 1 # same as result = result + 1
return result
print(count_chars(text))
到目前为止,这是在查找len()文本的总数而不是按单词查找。
我想得到类似函数 Counter 的东西,Counter()它返回单词以及它在整个文本中重复的次数。
from collections import Counter
word_count=Counter(text)
我想获得每个单词的字符数。一旦我们有了这样的计数,绘图应该会更容易。
谢谢和任何帮助!
回答
好的,首先你需要打开sample.txt文件。
with open('sample.txt', 'r') as text_file:
text = text_file.read()
或者
text = open('sample.txt', 'r').read()
现在我们可以计算文本中的单词并将其放入例如字典中。
counter_dict = {}
for word in text.split(" "):
counter_dict[word] = len(word)
print(counter_dict)