【问题标题】:How to find required word in novel in python?如何在python中找到小说中所需的单词?
【发布时间】:2021-08-07 22:18:08
【问题描述】:

我有一个文本,我在 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

【问题讨论】:

  • 如果您要求人们改进您的代码,请查看Code Review

标签: python string list text split


【解决方案1】:

试试这个:

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]

【讨论】:

    【解决方案2】:

    这可以使用正则表达式和捕获组轻松完成。

    查看here 以供参考,在这种情况下,您可能想做类似的事情

    # retrieve a list of strings that match your regex
    matches = re.findall("Mr\. ([a-zA-Z]+)", your_entire_file)  # not sure about the regex
    
    # then create a dictionary and count the occurrences of each match
    # if you are allowed to use modules, this can be done using Counter
    Counter(matches)
    

    要像这样访问整个文件,您可能需要将其映射到内存,请查看this question

    【讨论】:

    • 你不会处理像汤姆史密斯先生这样的名字
    • @rudolfovic 是的,我在写答案时没有考虑这种情况?
    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2018-10-11
    相关资源
    最近更新 更多