首页 > 解决方案 > 如何在 Python 的文本中查找哪些字符串(在一大串字符串中)?

问题描述

我正在尝试找出新闻文本中的列表名称。

我有一个包含许多地名的大文本文件(大约 100MB)。每个名称都是文件中的一行。

文件的一部分。

Brasiel
Brasier Gap
Brasier Tank
Brasiilia
Brasil
Brasil Colonial

新闻文本是这样的:

"It's thought the couple may have contracted the Covid-19 virus in the US or while travelling to Australia, according to Queensland Health officials.
Hanks is not the only celebrity to have tested positive for the virus. British actor Idris Elba also revealed last week he had tested positive."

例如,在本文中,字符串Australia 和Queensland 应该被创建。我正在使用 NLTK 库并从新闻中创建 ngram。

为此,我正在这样做:

from nltk.util import ngrams

# readings the place name file
file = open("top-ord.txt", "r")
values = file.readlines()

news = "It's thought the couple may have contracted the Covid-19 virus in the US or while travelling to Australia, according to Queensland Health officials."

# ngrams_list is all ngrams from the news
for item in ngrams_list:
    if item in values:
        print(item)

这太慢了。我该如何改进它?

标签: python-3.xnltkn-gram

解决方案


将值转换为这样的集合:

value_set = {country for country in values}

这应该会显着加快速度,因为使用集合的查找在恒定时间内运行(与使用列表的线性时间相反)

此外,请确保在解析文件时去掉尾随的换行符(如果需要)。


推荐阅读