Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何制作一个python程序,列出某个单词在句子中的位置_Python_Position_Analysis_Identify - Fatal编程技术网

如何制作一个python程序,列出某个单词在句子中的位置

如何制作一个python程序,列出某个单词在句子中的位置,python,position,analysis,identify,Python,Position,Analysis,Identify,我试图找出如何制作一个python程序,突出显示某个输入单词在句子中的位置,并列出该单词所在的位置。例如,如果句子是:“肥猫坐在垫子上” 那么单词fat的位置将是第2位 到目前为止,我得到的是: varSentence = ("The fat cat sat on the mat") print (varSentence) varWord = input("Enter word ") varSplit = varSentence.split() if varWord in varSpli

我试图找出如何制作一个python程序,突出显示某个输入单词在句子中的位置,并列出该单词所在的位置。例如,如果句子是:“肥猫坐在垫子上” 那么单词fat的位置将是第2位

到目前为止,我得到的是:

varSentence = ("The fat cat sat on the mat")

print (varSentence)

varWord = input("Enter word ")

varSplit = varSentence.split()

if varWord in varSplit:
    print ("Found word")
else:
    print ("Word not found")
用于将句子转换为单词列表、生成位置和生成结果列表

>>> sentence = "The fat cat sat on the mat"
>>> words = sentence.lower().split()
>>> word_to_find = "the"
>>> [pos for pos, word in enumerate(words, start=1) if word == word_to_find]
[1, 6]

如果找不到单词,结果将是一个空列表。

您可以使用此代码。我创建它是为了在学校完成一项任务,不过如果你把它分解一下,它应该会有所帮助

UserSen = input("Please type in a sentence without punctuation:")
print("User has input:",UserSen)
WordFindRaw = input("Please enter a word you want to search for in the sentence:")
print("The word requested to be seacrhed for is:",WordFindRaw)
UserSenLow = UserSen.lower()
WordFind = WordFindRaw.lower()
SenLst = []
SenLst.append(UserSenLow)
print(SenLst)
if any(WordFind in s for s in SenLst):
print("Search successful. The word '",WordFind,"' has been found in position(s):")
else:
print("Search unsuccessful. The word '",WordFind,"' was not found. Please try another word...")

任务的哪一部分你有问题?我有一个程序来分析句子中是否有一个单词,只是在尝试列出该单词的位置时遇到了困难。我们希望你开始解决这个问题,但你被阻止了,这就是你请求我们帮助的原因。所以我们的问题是:你被封锁在哪里?如果你的答案是“在开头”,那么你显然是在错误的地方。你在一张纸上写了一些算法吗?我将添加程序@cilyan到目前为止,你可能应该首先将句子拆分为单词,即将一个大字符串转换为一个小字符串列表,每个字符串包含一个单词。然后你逐字逐句,看看哪个是你要找的。