提问人:Helpme 提问时间:11/8/2023 最后编辑:mkrieger1Helpme 更新时间:11/8/2023 访问量:34
python 的字符串查找方法返回 -1 的问题
Issue with python's string find method returning -1
问:
我正在尝试编写一个接受字符串并返回标记位置的函数。该函数在以下情况下工作正常,但是如果我尝试使用字符串 lower 方法,如下面的代码所示,我的第一个元组返回 as 而不是所需的输出tokens = query_string.split()
[(-1, 2), (5, 6), (8, 8), (10, 13)]
[(0, 3), (5, 6), (8, 8), (10, 13)]
我用于测试的字符串是“This is a test”。
def token_position_list(query_string):
"""
:param query_string: a string representing a query
:return: a list of tuples, where each tuple holds the start and end positions of each token
"""
token_positions = []
tokens = query_string.lower().split()
current_position = 0
for token in tokens:
start_position = query_string.find(token, current_position)
end_position = start_position + len(token) - 1
token_positions.append((start_position, end_position))
current_position = end_position + 1
return token_positions
谁能向我解释为什么加低会这样做以及我如何解决这个问题?
答:
0赞
Barmar
11/8/2023
#1
您的所有令牌都是小写的,但仍然是混合大小写的。因此,如果原始字符串在该标记中包含任何大写字母,则它不会找到该标记。query_string
您应该转换为小写并对其进行处理。query_string
def token_position_list(query_string):
"""
:param query_string: a string representing a query
:return: a list of tuples, where each tuple holds the start and end positions of each token
"""
token_positions = []
query_string = query_string.lower()
tokens = query_string.split()
current_position = 0
for token in tokens:
start_position = query_string.find(token, current_position)
end_position = start_position + len(token) - 1
token_positions.append((start_position, end_position))
current_position = end_position + 1
return token_positions
评论
0赞
Helpme
11/8/2023
天哪,谢谢,这是我第一次在 python 中使用 find,我陷入了思考,认为我可能用错了,以至于我没有看到。非常感谢!
评论
This is a test
query_string.lower().split()
token
for token in tokens:
this
This is a test