我想检查单词列表是否在字符串中。
例如:
SELECT
DateReceived ,
UniqueNumber ,
TransferDate ,
CompanyCode
FROM
ExportData
WHERE YEAR(CONVERT(DATETIME, TransferDate)) =
(
SELECT YEAR(MAX(CONVERT(DATETIME, TransferDate)))
FROM TransferDate
)
ORDER BY TransferDate DESC;
字符串1为true,因为它包含'hi',而字符串2为false,因为它不包含'hi'。
我尝试了以下代码,但始终返回false。
listofwords = ['hi','bye','yes','no']
String = 'Hi how are you'
string2 = 'I have none of the words'
我还想证明匹配的单词是什么,以检查它是否正确。
答案 0 :(得分:5)
hi
和Hi
是不同的词。比较之前使用.lower
。
if any(ext.lower() in String.lower() for ext in listofwords):
print(String)
更新:
示例:
listofwords = ['hi','bye','yes','no']
String = 'Hi how are you'
string2 = 'I have none of the words'
for word in listofwords:
if word.lower() in map(str.lower,String.split()): # map both of the words to lowercase before matching
print(word)
for word in listofwords:
if word.lower() in map(str.lower,string2.split()): # map both of the words to lowercase before matching
print(word)
PS:不是优化版本。您可以将String.split
结果存储在列表中,然后开始进行迭代,这将节省较大字符串的时间。但是该代码的目的是演示lower
大小写的用法。
答案 1 :(得分:2)
Python区分大小写。因此hi不等于Hi。这有效:
listofwords = ['hi','bye','yes','no']
String = 'hi how are you'
string2 = 'I have none of the words'
if any(ext in String for ext in listofwords):
print(String)
答案 2 :(得分:0)
问题在于区分大小写和直接对字符串使用in
。
如果要使搜索不区分大小写,请考虑将String
和单词都转换为小写,此外,如果要正确搜索单词,则应在字符串后用小写大写字母分割:
if any(ext.lower() in String.lower().split() for ext in listofwords):
print(String)
拆分避免为True
中的no
之类的字符串返回none
,并且仅在no
(或任何其他单词)单独存在时才起作用。因此,以上内容对String
(将打印它)和string2
(将不会打印)都适用。