我的目标是在两个对齐的文本文档中识别匹配的字符串,然后在每个文档中找到匹配字符串的起始字符的位置。
doc1=['the boy is sleeping', 'in the class', 'not at home']
doc2=['the girl is reading', 'in the class', 'a serious student']
我的尝试:
# find matching string(s) that exist in both document list:
matchstring=[x for x in doc1 if x in doc2]
Output=matchstring='in the class'
现在的问题是找到doc1和doc2中匹配字符串的字符偏移量(不包括标点符号,包含空格)。
理想的结果:
Position of starting character for matching string in doc1=20
Position of starting character for matching string in doc2=20
有关文字对齐的任何想法吗?感谢。
答案 0 :(得分:1)
doc1=['the boy is sleeping', 'in the class', 'not at home']
doc2=['the girl is reading', 'in the class', 'a serious student']
temp=''.join(list(set(doc1) & set(doc2)))
resultDoc1 = ''.join(doc1).find(temp)
resultDoc2 = ''.join(doc2).find(temp)
print "Position of starting character for matching string in doc1=%d" % (resultDoc1 + 1)
print "Position of starting character for matching string in doc2=%d" % (resultDoc2 + 1)
它完美地符合您的期望!