python - 如何在python中找到小说中所需的单词?
问题描述
我有一个文本,我在 python 中有一个阅读模块的任务:
查找被称为 的人的姓名Mr. XXX
。将结果保存在字典中,名称为键,使用次数为值。例如:
- 如果丘吉尔先生在小说中,则包括
{'Churchill' : 2}
- 如果弗兰克丘吉尔先生在小说中,那么包括
{'Frank Churchill' : 4}
该文件为 .txt,包含大约 10-15 个段落。
您对如何改进有想法吗?(在一些话之后它给了我错误,我猜错误是由于其中一个Mr.
在行尾的原因而发生的。)
orig_text= open('emma.txt', encoding = 'UTF-8')
lines= orig_text.readlines()[32:16267]
counts = dict()
for line in lines:
wordsdirty = line.split()
try:
print (wordsdirty[wordsdirty.index('Mr.') + 1])
except ValueError:
continue
解决方案
尝试这个:
text = "When did Mr. Churchill told Mr. James Brown about the fish"
m = [x[0] for x in re.findall('(Mr\.( [A-Z][a-z]*)+)', text)]
你得到:
['Mr. Churchill', 'Mr. James Brown']
要解决线路问题,只需阅读整个文件:
text = file.read()
然后,要计算出现次数,只需运行:
Counter(m)
最后,如果您想'Mr. '
从所有字典条目中删除,请使用x[0][4:]
而不是x[0]
.
推荐阅读
- node.js - 我如何在 LAMDA Nodejs 中随机播放数组?
- r - 将行批量转置到 R 中的列
- ios - 在 SceneKit 中查找节点引用
- angular - 使用 EventEmitter 角度发射一个值
- r - 如何在 R 的数据框中搜索和压缩重复行?
- bash - 如何将存储为文本的数字划分为 awk 或 sed 或其他的许多部分?
- python - 正则表达式python中的表达式
- api - URL 参数作为 null 传递,而不是预期传递的参数
- java - 在 android studio 中安装 genymotion 时遇到问题
- python - 将 europarl 模块/数据集导入 python 的问题