我创建了这段代码来分析一个输入句子,以便用户在其中搜索某个单词。然而,我似乎不知道如何使它在输入句子中的所有标点符号被忽略。我之所以需要这样做是因为,如果输入“hello there,friend”这样的句子,“there”这个词就被算作“there”,因此如果用户正在搜索“there”,它会说它不在句子中。请帮帮我。我对python真的很陌生。你知道吗
print("Please enter a sentence")
sentence=input()
lowersen=(sentence.lower())
print(lowersen)
splitlowersen=(lowersen.split())
print (splitlowersen)
print("Enter word")
word=input()
lword=(word.lower())
if lword in splitlowersen:
print(lword, "is in sentence")
for i, j in enumerate (splitlowersen):
if j==lword:
print(""+lword+"","is in position", i+1)
if lword not in splitlowersen:
print (lword, "is not in sentence")
输出:
这可能有点冗长,但在Python3。你知道吗
这里有一些先进的概念。你知道吗
Filter将接受一个函数和一个iterible,该函数和iterible返回一个生成器,其中的项不会从函数返回true https://docs.python.org/3/library/functions.html#filter
Lambda将创建一个匿名函数,为我们检查每个字母。 https://docs.python.org/3/reference/expressions.html#lambda
isalpha()将检查所讨论的字母是否是一个字母。 后跟x=='',可以看到它可能是一个空格。 https://docs.python.org/3.6/library/stdtypes.html?highlight=isalpha#str.isalpha
''。join将获取筛选器的结果并将其放回字符串中。 https://docs.python.org/3.6/library/stdtypes.html?highlight=isalpha#str.join
您可以拆分所有标点符号上的字符串:
相关问题 更多 >
编程相关推荐