python - 从文本文件计算词频,但我的输出中有错误
问题描述
从文件中读取所有行并使用 split() 方法将这些行拆分为单词。strip("""!"#$%&'()*,-./:;?@[]_""")
此外,使用方法调用从单词末尾删除标点符号
我是python的初学者并试图解决一些基本问题,我在给出的问题中使用了split和strip函数,但是我在某些单词的频率上出现错误,请查看我的代码。
蟒蛇代码:
def word_frequencies(filename="alice.txt"):
with open(filename) as f:
string=f.read()
words=string.split()
l=[]
for word in words:
temp=word.strip("""!"#$%&'()*,-./:;?@[]""")
if temp:
l.append(temp)
string2=[]
for i in l:
if i not in string2:
string2.append(i)
for j in string2:
print(f"{j}\t{l.count(j)}")
输出:
The 64
Project 83
Gutenberg 27
EBook 3
of 303
. . . 等等。
但实际输出是:
The 64
Project 83
Gutenberg 26
EBook 3
of 303
. . . 等等
解决方案
使用re.findall拆分为单词:
from re import findall
words = findall(r"\b\w+\b", text)
,其中text是您的f.read()。
然后数一数:
from collections import Counter
c = Counter(words)
检查字数:
for word in ("The", "Project", "Gutenberg", "EBook",):
print(word, c[word])
印刷:
The 64
Project 83
Gutenberg 83
EBook 3
推荐阅读
- java - 从数据库存储和检索数据的最佳方法是什么
- antlr4 - 在 antlr4 解析语法中使用文字?
- c# - 是否可以在谷歌浏览器上的网络浏览器上输入 url 并将值返回到网络浏览器时访问 Windows 应用程序功能
- javascript - 在 Open Layers 中添加点,并在指针单击坐标的实际位置下方绘制几个像素
- python - 如何使用 cx_Oracle Python 连接到 Oracle ODBC 数据源?
- html - 在移动视图中对齐引导程序 4 列
- android - 捕获所有 AdMob 崩溃?
- android - 回收站查看物品装饰和查看标高
- javascript - 使用 JavaScript/PHP 调整图像画布大小
- ios - 在文本视图中使用 separatorBy 函数获取范围