python-3.x - 如何在 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)
这太慢了。我该如何改进它?
解决方案
将值转换为这样的集合:
value_set = {country for country in values}
这应该会显着加快速度,因为使用集合的查找在恒定时间内运行(与使用列表的线性时间相反)
此外,请确保在解析文件时去掉尾随的换行符(如果需要)。
推荐阅读
- java - 如何从日历对话框中获取相关的星期几而不是先前选择的日期
- android-studio - 从 Android-Studio 运行时,应用程序给出安装失败的错误
- git - Intellij IDE - 在 GIT 分支之间切换时删除文件夹
- python - 基于另一个 Django 模型的多个字段检索唯一 Django 对象的计数
- javascript - 如何创建目录树的基于 JavaScript 对象的表示
- c# - 如何在ac#类中设置数据(多类)
- java - 当我按下点按钮时,我希望该点按钮在输入 1 中只按下一次?
- php - Wordpress - 如何删除包含断开链接的元 og:图像?
- angular - ngx-international-phone-number 删除国家代码或使其不可编辑
- c# - 带有文件创建选项的 OpenFileDialog