python-3.x - 如何识别 prargraph 中存在 2 个不同的字符串
问题描述
我有 2 个不同的列表,其中包含名称和位置。需要在文本中识别名称和位置的位置。
输入
名称:['Mughal'] 地点:['Panipat','Agra']
text=['帕尼帕特战役奠定了阿格拉莫卧儿王朝的基础。']
输出:
开始位置:15;结束位置:21;字:Panipat;类型:位置;开始位置:50;结束位置:55;字:莫卧儿;类型:姓名
代码:
for t in (text):
for n in name_:
while index_ < len(t):
index_ = t.find(n,index_)
if index_ == -1:
break
else:
kwmatch.append((index_, index_+len(n),"Name"))
index_ += len(rect)
index_ = 0
a = (text,{'entities':kwmatch})
doctuple.append(a)
kwmatch = []
a = None
解决方案
首先,如果您要使用字典(https://docs.python.org/3/tutorial/datastructures.html#dictionaries) ,保存您Name
的数据会容易得多。例如Location
dct = {
'Name' : ['Mughal'],
'Location': ['Panipat','Agra']
}
之后,您可以遍历文本列表中的每个文本,使用string.find查找单词的开始和结束索引,并且可以从正在搜索的单词和键中获取单词和类型。
text=['The battle of Panipat laid the foundation of the Mughal dynasty in Agra.']
for t in text:
for key, value in dct.items():
for v in value:
#Starting index using find
start_pos = t.find(v)+1
#Ending index after adding the length of word
end_pos = start_pos+len(v)-1
#Word and type are the word we are looking for, and the key of the dictionary
print('Start position: {}; end position: {}; Word: {}; type: {}'.format(start_pos, end_pos, v, key))
然后输出出现。
Start position: 50; end position: 55; Word: Mughal; type: Name
Start position: 15; end position: 21; Word: Panipat; type: Location
Start position: 68; end position: 71; Word: Agra; type: Location
推荐阅读
- laravel - 在 laravel 8 上需要帮助 .. 无法打开流错误
- google-apps-script - 在 Google 表格中制作一个闪烁的单元格
- flutter - 当 Flutter 中的 barrierDismissible=true 时,如何在 Modal 外部点击时将结果作为参数提供给 ModalRoute 类?
- javascript - Sequelize过滤器关联数据
- html - 位置固定的下拉菜单悬停不起作用
- bash - 如何将标准输出/标准错误从源命令捕获/重定向到变量中(在 bash 脚本中)?
- postgresql - 如何在function2中返回function1结果的COUNT
- java - Firestore 按 UserId 排序,优先级最高
- python - 解析为结构化类实例的 Python 模式包
- python - 获取 json/dict 字符串的值