我得到了一个带有文本的 .txt 文件。我已经清理了文本(删除了标点符号、大写字母、符号),现在我有了一个包含单词的字符串。
我现在正在尝试获取字符串中每个项目的字符数 len()
。然后绘制一个图,其中 N 个字符在 X 轴上,Y 轴是具有这样的 N len()
个字符的单词数
到目前为止我有:
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)
关于Python 按字长计算字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67087535/