【问题标题】:Exact word match using index or find method - python使用索引或查找方法精确匹配单词 - python
【发布时间】:2016-11-15 06:45:13
【问题描述】:

我有一个字符串“the then there”,我想搜索准确/完整的单词,例如在这种情况下,“the”只出现一次。但是使用 index() 或 find() 方法认为出现了 3 次,因为它也与 "then" 和 "there" 部分匹配。我喜欢使用这两种方法中的任何一种,有什么方法可以调整它们以使其工作吗?

>>> s = "the then there"
>>> s.index("the")
0
>>> s.index("the",1)
4
>>> s.index("the",5)
9
>>> s.find("the")
0
>>> s.find("the",1)
4
>>> s.find("the",5)
9

【问题讨论】:

  • 使用正则表达式\bthe\b

标签: python indexing find


【解决方案1】:

要在大文本中找到准确/完整单词的第一个位置,请尝试使用re.search()match.start() 函数应用以下方法:

import re

test_str = "when we came here, what we saw that the then there the"
search_str = 'the'
m = re.search(r'\b'+ re.escape(search_str) +r'\b', test_str, re.IGNORECASE)
if m:
    pos = m.start()
    print(pos)

输出:

36

https://docs.python.org/3/library/re.html#re.match.start

【讨论】:

    【解决方案2】:

    首先使用str.split()将字符串转换为单词列表,然后搜索单词。

    >>> s = "the then there"
    >>> s_list = s.split() # list of words having content: ['the', 'then', 'there']
    >>> s_list.index("the")
    0
    >>> s_list.index("then")
    1
    >>> s_list.index("there")
    2
    

    【讨论】:

    • 性能对我的用例来说是一个问题,因为它可能是一个非常大的文件,因此试图避免列出一个庞大的列表......
    • 无论如何这是一个巨大的文件。您需要将其存储为strlist,但您需要将其存储在某个地方。正确的?将内容读取为字符串,形成一个列表。如果您对节省空间更感兴趣。获得列表后,将其转换为字典,以单词为键,值作为该单词第一次出现的索引。显式删除未使用的变量,例如存储字符串和列表的变量
    猜你喜欢
    • 2019-08-09
    • 1970-01-01
    • 2021-10-25
    • 2011-08-10
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    相关资源
    最近更新 更多