0

如何将整个文本文件作为数据块或字符串读取?我不想逐行读取文件,而是将整个文件作为文本读取并查找某些单词的计数。这样做的方法是什么?

4

4 回答 4

2

您可以使用文件read()函数“读取一定数量的数据并将其作为字符串返回”。

文档在这里

于 2013-10-12T19:50:05.860 回答
1

至于第二个问题,您可能希望使用带有单词边界锚点的正则表达式:

import re
with open("myfile.txt") as infile:
    text = infile.read()
regex = re.compile(r"\bsearchword\b", re.I) # case-insensitive
count = len(regex.findall(text))
于 2013-10-12T19:52:42.853 回答
0

You can read it line by line, count the words you are interested in on each line, add the results to the subtotal, and print the total when you are done. Handy if the file you are processing is big enough to cause swapping.

于 2013-10-12T20:16:50.163 回答
0

withopen.read一起使用:

with open("/path/to/file") as file:
    text = file.read()

with是一个上下文管理器,它会在完成后为您自动关闭文件。

于 2013-10-12T19:52:16.990 回答