python - 如何使用 python 查找文本中的字符偏移量

标签 python string text

我的目标是识别两个对齐的文本文档中的匹配字符串,然后找到每个文档中匹配字符串的起始字符的位置。

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

关于文本对齐有什么想法吗?谢谢。

最佳答案

嘿伙计,试试这个:

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)

它完美地符合您的期望!

关于python - 如何使用 python 查找文本中的字符偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132192/

相关文章:

python - 在 Jinja2 中使用 "{{ field(class=...) }}"安全吗?

python - Django:使用 FormView 时可能有多种形式?

使用 xrange 进行 Python 字符串操作

c++ - 从 txt 文件读取行后字符串比较失败

Python:在字符串中查找子字符串并返回子字符串的索引

java - 从文本文件中删除一个单词

python - Python中的多线程(我的代码正确)

python - 当泡沫工作完成时如何向自己发送电子邮件通知?

C# 如何在文本文件中写入多行?

javascript - <p> 或 <span> 没有字符时,如何提供默认字体高度或内容?