在python中查找文件中的字数

2024-05-01 21:47:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,尝试做一个练习,打开一个txt文件,然后读取其中的内容(对于大多数人来说可能是直截了当的,但我承认我有点困难)。你知道吗

我打开文件并使用.read()读取文件。然后,我继续移除任何穿刺的文件。 接下来我创建了一个for循环。在这个循环中,我开始使用.split()并向表达式中添加: 单词=单词+长度(字符) 循环外先前定义为0的单词和循环开头拆分的字符。 长话短说,我现在遇到的问题是,不是将整个单词添加到我的计数器中,而是添加每个单独的字符。我能做些什么来解决我的for循环中的问题吗?你知道吗

my_document = open("book.txt")
readTheDocument = my_document.read
comma = readTheDocument.replace(",", "")
period = comma.replace(".", "")
stripDocument = period.strip()

numberOfWords = 0 

for line in my_document:
splitDocument = line.split()
numberOfWords = numberOfWords + len(splitDocument)


print(numberOfWords)

Tags: 文件txtforreadmyline字符单词
2条回答

只需打开文件并拆分即可得到字数。你知道吗

file=open("path/to/file/name.txt","r+")
count=0
for word in file.read().split():
    count = count + 1
print(count)

一种更具python风格的方法是使用with

with open("book.txt") as infile:
    count = len(infile.read().split())

你必须明白,通过使用.split(),你并不是真的得到了真正的语法单词。你得到的是字里行间的碎片。如果您想要合适的单词,请使用模块nltk

import nltk
with open("book.txt") as infile:
    count = len(nltk.word_tokenize(infile.read()))

相关问题 更多 >