【问题标题】:Python - Check if a word is in a string [duplicate]Python - 检查一个单词是否在字符串中[重复]
【发布时间】:2021-04-04 02:34:51
【问题描述】:

如何判断一个单词是否在字符串中?

  • 单词不是子字符串。
  • 我不想使用正则表达式。

仅使用in 是不够的...

类似:

>>> wordSearch('sea', 'Do seahorses live in reefs?')
False
>>> wordSearch('sea', 'Seahorses live in the open sea.')
True

【问题讨论】:

标签: python python-3.x string


【解决方案1】:

不忘大小写,分割字符串,去掉单词标点怎么办?

w in [ws.strip(',.?!') for ws in p.split()]

也许是这样:

def wordSearch(word, phrase):
    punctuation = ',.?!'
    return word in [words.strip(punctuation) for words in phrase.split()]

    # Attention about punctuation (here ,.?!) and about split characters (here default space)

示例:

>>> print(wordSearch('Sea'.lower(), 'Do seahorses live in reefs?'.lower()))
False
>>> print(wordSearch('Sea'.lower(), 'Seahorses live in the open sea.'.lower()))
True

我将 case 转换移至函数调用以简化代码...
而且我没有检查表演。

【讨论】:

  • 一个单词在一个字符串中对于第一个例子来说可能是真的
【解决方案2】:

使用in 关键字:

类似这样的:

print('Sea'in 'Seahorses live in the open sea.')

如果您不希望它区分大小写。将所有字符串转换为lowerupper

类似这样的:

string1 = 'allow'
string2 = 'Seahorses live in the open sea Allow.'

print(string1.lower() in string2.lower())

或者您可以像这样使用find 方法:

string1 = 'Allow'
string2 = 'Seahorses live in the open sea Allow.'

if string2.find(string1) !=-1 :
    print('yes')

如果要匹配确切的单词:

string1 = 'Seah'
string2 = 'Seahorses live in the open sea Allow.'

a = sum([1 for x in string2.split(' ') if x == string1])

if a > 0:
    print('Yes')

else:
    print('No')

更新

你需要忽略所有的标点符号所以使用这个。

def find(string1, string2):
    lst = string2.split(' ')
    puctuation = [',', '.', '!']
    lst2 = []
    
    for x in lst:
        for y in puctuation:
            if y in x[-1]:
                lst2.append(x.replace(y, ''))
        lst2.append(x)
    
    lst2.pop(-1)    
    a = sum([1 for x in lst2 if x.lower() == string1.lower()])
    if a > 0:
        print('Yes')
    
    else:
        print('No')

find('sea', 'Seahorses live in the open sea. .hello!')

【讨论】:

  • in 关键字也查找子字符串,所以它也会匹配 seahorse...不好...
  • @marcio 哪一个?最后一个?
  • 他的意思是一个被边界包围的词,而不是一个子字符串
  • @marcio 请注意区分大小写。
  • @marcio 它对我来说非常好用有什么问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 2016-12-05
  • 2020-02-17
  • 1970-01-01
  • 2014-08-09
  • 2016-06-27
相关资源
最近更新 更多