Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python查找文本中的字符偏移量_Python_String_Text - Fatal编程技术网

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

如何使用python查找文本中的字符偏移量,python,string,text,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: matchstri

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

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)

它完全符合您的期望

为什么我发现它是19而不是21?嗨@zhangxaochen,你在“sleep”中停止在字符“g”处计数,而不是在类中停止在字符“I”处。《男孩在睡觉》的长度是19,
I
是第20个字符,如果从0索引,则位于位置19。如果从零索引,则你是对的,那么字符偏移量就是第20个字符。请让我看看你的方法好吗?@zhangxaochen,你能告诉我你是怎么做的吗?任何人都可以通过主视图进行索引。Al Mamun,谢谢你的解决方案。正如你所说,它工作得很好。@Al Mamum,我仍然希望我能得到一个两行代码的答案。在真正的文档中,必须有“\n”或类似的解释。由于“\n”和“\n\r”(windows与linux的行尾)会影响文件中的偏移量,因此需要技巧。在这种情况下,请使用正则表达式:)