首页 > 解决方案 > 如何在python中找到小说中所需的单词?

问题描述

我有一个文本,我在 python 中有一个阅读模块的任务:

查找被称为 的人的姓名Mr. XXX。将结果保存在字典中,名称为键,使用次数为值。例如:

该文件为 .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

标签: pythonstringlisttextsplit

解决方案


尝试这个:

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].


推荐阅读