Python字符串搜索:如何查找精确匹配,而不是与包含搜索字符串的字符串匹配

2024-05-16 00:52:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要我的脚本为不同的词给出定义

我使用一个循环来查找字符串(X)和数组中的项之间的匹配

if any(i in X for i in ('coconut, Coconut')):
    print("found coconut")

if any(i in X for i in ('nut', 'Nut')):
    print("found nut")

问题是,当数组X中的项是一个包含另一个字的字(例如couch&;nut)时,两个打印都会执行

我如何确保当数组X中有一个名为couch的项目时,我只得到couch的打印,而不是nut的打印

我将永远感激你的帮助


Tags: 字符串in脚本forif定义any数组
3条回答

这应该可以用-i在X中测试是否在字符串X中找到子字符串i,同时测试它们是否等价

if any(i == X for i in ('nut', 'Nut'):
    print('found nut')

您可以将字符串X转换为一个集合:

sx = set(X.split()) # to get the words you may use a regex, depending of how X looks
if sx & {'coconut, Coconut'}:
    print("found coconut")

您可以测试单个字符串是否相等,而不是X数组中是否存在单词(在python中通常称为list,除非您使用numpy):

if any(i == x for i in ('coconut', 'Coconut') for x in X):
    print("found coconut")

if any(i == x for i in ('nut', 'Nut') for x in X):
    print("found nut")

或者更好的是,您可以先将测试字符串转换为小写,这样每个单词只需要一个for循环:

if any(x.lower() == "coconut" for x in X):
    print("Found coconut")

除非您想要区分专有名词,例如为Jersey和Jersey提出不同的定义,否则这是有效的

如果X是一个字符串,则简单的相等性检查将适用于此:

if X.lower() == "coconut":
    print("Found coconut")

相关问题 更多 >