Python 查找单词在字符串中的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33053641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the position of a word in a string
提问by Erjonk2001
With:
和:
sentence= input("Enter a sentence")
keyword= input("Input a keyword from the sentence")
I want to find the position of the keyword in the sentence. So far, I have this code which gets rid of the punctuation and makes all letters lowercase:
我想找到关键字在句子中的位置。到目前为止,我有这个去掉标点符号并使所有字母小写的代码:
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''#This code defines punctuation
#This code removes the punctuation
no_punct = ""
for char in sentence:
if char not in punctuations:
no_punct = no_punct + char
no_punct1 =(str.lower (no_punct)
I know need a piece of code which actually finds the position of the word.
我知道需要一段代码来实际找到单词的位置。
回答by Kasramvd
This is what str.find()
is for :
这是什么str.find()
:
sentence.find(word)
This will give you the start position of the word (if it exists, otherwise -1), then you can just add the length of the word to it in order to get the index of its end.
这将为您提供单词的开始位置(如果存在,否则为 -1),然后您只需将单词的长度添加到它即可获得其结尾的索引。
start_index = sentence.find(word)
end_index = start_index + len(word) # if the start_index is not -1
回答by paolo
If with position you mean the nth word in the sentence, you can do the following:
如果使用 position 表示句子中的第 n 个单词,则可以执行以下操作:
words = sentence.split(' ')
if keyword in words:
pos = words.index(keyword)
This will split the sentence after each occurence of a space and save the sentence in a list (word-wise). If the sentence contains the keyword, list.index()will find its position.
这将在每次出现空格后拆分句子并将句子保存在列表中(逐字)。如果句子包含关键字,list.index()会找到它的位置。
EDIT:
编辑:
The if statement is necessary to make sure the keyword is in the sentence, otherwise list.index() will raise a ValueError.
if 语句是必要的,以确保关键字在句子中,否则 list.index() 将引发 ValueError。