Python 使用用户定义词典标记句子中的单词

Python 使用用户定义词典标记句子中的单词,python,dictionary,ner,Python,Dictionary,Ner,我有一个超过10万个句子的语料库和一本字典。我想匹配语料库中的单词,并在句子中标记它们 语料库文件“testing.txt” 字典文件“dict.csv” 我的python程序 import csv from difflib import SequenceMatcher as SM from nltk.util import ngrams import codecs with open('dictionary.csv','r') as csvFile: reader = csv.re

我有一个超过10万个句子的语料库和一本字典。我想匹配语料库中的单词,并在句子中标记它们

语料库文件“testing.txt”

字典文件“dict.csv”

我的python程序

import csv
from difflib import SequenceMatcher as SM
from nltk.util import ngrams

import codecs

with open('dictionary.csv','r') as csvFile:
    reader = csv.reader(csvFile)
    myfile = open("testing.txt", "rt")
    my2file = open("match.txt" ,"w")
    hay = myfile.read()
    myfile.close()

for row in reader:
    needle = row[1]
    needle_length = len(needle.split())
    max_sim_val = 0.9
    max_sim_string = u""
    for ngram in ngrams(hay.split(), needle_length + int(.2 * needle_length)):
        hay_ngram = u" ".join(ngram)

        similarity = SM(None, hay_ngram, needle).ratio()
        if similarity > max_sim_val:
            max_sim_val = similarity
            max_sim_string = hay_ngram
            str = [row[1] , ' ', max_sim_val.__str__(),' ', max_sim_string , '\n']
            my2file.writelines(str)
            print(str)

csvFile.close()
我现在的输出是

 disorder 0.9333333333333333 anxiety
 virus 0.9333333333333333 Malaria
我希望我的输出为

 Hello how are you doing. HIV [virus] is dangerous
 Malaria [virus] can be cure.
 he has anxiety [disorder] thats why he is behaving like that

您可以在
testing.txt
上的行上迭代并替换这些值,类似这样的操作应该可以:

。。。
如果相似性>最大模拟值:
max_sim_val=相似性
最大模拟字符串=hay\u ngram
str=[第[1]行,'',最大模拟值。''最大模拟值(),'',最大模拟字符串,'\n']
my2file.writelines(str)
打印(str)
对于干草中的线。拆分线():
如果行中有max_sim_字符串:
打印(line.replace(max_sim_string,f“{max_sim_string}[{row[1]}]”)
打破

比你兄弟,它真的帮了我一个大忙,我的文本是这样的格式{你好,你好。艾滋病毒很危险}{疟疾可以治愈}{他有焦虑,这就是他为什么这样做的原因。}{我做得很好}而我在{他有焦虑[紊乱]]中得到新文件的输出,这就是他为什么这样做的原因。{我做得很好{疟疾[病毒]可以治愈}{你好,头痛[症状]很危险}句子放错地方了。可以在“.txt”中保持相同的句子顺序吗归档并替换单词?是的,问题是您正在基于
dict.csv
构建输出,这是您应该获得的顺序。当然,它可以更改。为它创建一个问题,因为在注释中回答它非常复杂。@Subhaankhan感谢您的持续帮助。我将创建另一个问题谢谢。请看一下我的问题。谢谢
 disorder 0.9333333333333333 anxiety
 virus 0.9333333333333333 Malaria
 Hello how are you doing. HIV [virus] is dangerous
 Malaria [virus] can be cure.
 he has anxiety [disorder] thats why he is behaving like that