【问题标题】:How to find character offsets in texts using python如何使用python查找文本中的字符偏移量
【发布时间】:2014-03-02 19:20:54
【问题描述】:

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

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

关于文本对齐的任何想法?谢谢。

【问题讨论】:

  • 为什么我发现它是 19 而不是 21?
  • 嗨@zhangxaochen,你在'sleeping'中停止计数'g'而不是'in the class'中的'i'。
  • “男孩正在睡觉”的长度为 19,i 是第 20 个字符,如果从 0 开始索引,则位于位置 19。
  • 你是对的'如果从零开始索引',那么字符偏移量是第 20 个字符。请问我可以看看你的方法吗?
  • @zhangxaochen,你能告诉我你是怎么做的吗?任何人都可以通过主要查看索引。

标签: python string text


【解决方案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)

它完全符合您的期望!

【讨论】:

  • Al Mamun,感谢您的解决方案。正如你所说,它工作得很好。
  • @Al Mamum,我仍然希望我能得到一个两行代码的答案。
  • 在真实文档中必须有“\n”或类似的说明。棘手,因为“\n”和“\n\r”(windows vs linux 行尾)会影响文件中的偏移量。
  • 在这种情况下使用正则表达式:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-08
相关资源
最近更新 更多