Python 如何计算.txt文件中有多少个单词

Python 如何计算.txt文件中有多少个单词,python,Python,好的,我知道如何计算字符串中有多少个单词(o=len(x.split())print(o)),但如何计算.txt文件中有多少个单词 顺便说一句,我的代码如下所示: p = open("einsteinsbiography", "r", encoding="utf8") x = dict() for line in p: line = line.strip() line = line.lower() t = lin

好的,我知道如何计算字符串中有多少个单词(
o=len(x.split())print(o)
),但如何计算.txt文件中有多少个单词

顺便说一句,我的代码如下所示:

p = open("einsteinsbiography", "r", encoding="utf8")
x = dict()
for line in p:
    line = line.strip()
    line = line.lower()
    t = line.split(" ")
    for word in t:
        if word in x:
            x[word] = x[word] + 1
        else:
            x[word] = 1
for key in list(x.keys()):
    print(key, ":", x[key])

    

要仅获取文件中的总字数,请执行以下操作:

with open("einsteinsbiography", "r", encoding="utf8") as p:
    txt = p.read()
words = txt.split()
print(len(words))
如果要获取包含文件中每个单词计数的dict,请使用:


文本文件中的字数

num_chars = sum(len(word) for word in open('names.txt').read().split())
print(num_chars)

内存友好的细微变化(它逐行迭代.txt文件,而不是一次加载所有文件):


如果你想计算每个单词的实例数,我推荐big_bad_bison的答案,并使用反对象。

是你问题的答案吗?这是否回答了你的问题?好的,那么当你试图运行代码时发生了什么?这与应该发生的情况有何不同?您在描述中提供的行只计算单词总数,但您的代码似乎正在为每个唯一的单词建立单独的计数。当然,这是两件不同的事情……除了在字符串上计算单词数是在计算单词总数,而文件计数是在计算每个单词之外——你的问题是什么?我看到了一个代码,通过查看它,它做了它似乎应该做的事情。。。你的问题是什么?
txt.split(“”)
将只在空格上拆分,而不在换行符上拆分。我想您需要
txt.split()
,它将在所有空格上拆分。这也将连续的空白字符分组在一起,而不是向列表中添加空条目。
num_chars = sum(len(word) for word in open('names.txt').read().split())
print(num_chars)
with open("einsteinsbiography", "r", encoding="utf-8") as file:
    total = 0
    for line in file:
        # Remove all kinds of trailing whitespace with rstrip method
        total += len((line.rstrip()).split(' '))
print(total)