【问题标题】:how to identify 2 differnet strings exists in a prargraph如何识别段落中存在2个不同的字符串
【发布时间】:2019-09-10 05:35:59
【问题描述】:

我有 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

【问题讨论】:

  • 你能告诉我们你到目前为止已经做了什么吗?然后,社区可以帮助您编写代码。谢谢
  • @muralidhar A 你试试这个stackoverflow.com/questions/250271/…
  • @Gagan 写的列表无法理解,将其转换为多个列表
  • 你可以用字典让你的生活更轻松,看看我的回答是否对你有帮助

标签: python-3.x text spacy


【解决方案1】:

首先,如果您要使用字典 (https://docs.python.org/3/tutorial/datastructures.html#dictionaries),保存您的 NameLocation 数据会容易得多。例如

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 2019-11-20
    相关资源
    最近更新 更多