如何使用.split,枚举和列表来查找句子中单词的位置

时间:2016-05-14 15:13:49

标签: python python-3.x

我被要求从输入句中找到输入单词的位置,我无法弄清楚如何一起使用枚举,.split和列表。这就是我到目前为止所做的:

sntc=str(input("Please input a sentence with no punctuation."))
wrd=str(input("Please input a word from that sentence."))
words=sntc.split
list(enumerate(sntc))
for x in y in enumerate:
    if x==(wrd):
        print ("The chosen word is in postion(s):",x+1)

4 个答案:

答案 0 :(得分:1)

您不需要将输入转换为str。它已经是一个字符串。

words并不是您的想法。所有这一切都是对split方法的引用。你永远不会调用方法split

e.g。 -

>>> a_string = "Look a  string"
>>> print(a_string.split)
>>> <built-in method split of str object at (memory address)>

调用拆分,我们有:

>>> print(a_string.split())
>>> ['Look', 'a', 'string']

目前还不清楚你在枚举和words = sntc.split以下的所有内容中尝试实现的目标。我认为您实际上想要对sntc进行枚举,并检查给定的wrd是否与此拆分列表中的项匹配。

还有另一个问题,枚举返回iterable中的索引和iterable中的项,这里的索引(位置)将只是这个列表中的位置(单词)+ 1.

不是句子中的实际位置

e.g。 -

>>> sntc = input("Please input a sentence with no punctuation: ")
Please input a sentence with no punctuation: Look a sentence
>>> wrd = input("Please input a word from that sentence: ")
Please input a word from that sentence: a
>>> words = sntc.split()

单词= ['Look', 'a', 'sentence']。 &#39; a&#39;的位置在这里是1。

>>> for i, word in enumerate(words):
...      if word == wrd:
...          print("Chosen word is in position %d" % (i + 1))
...
Chosen word is in position 2 #Position of 'a' + 1

你真正想要的是:

for word in words:
    if word == wrd:
        print("Position is %d" % sntc.index(word))

答案 1 :(得分:0)

这是您正在寻找的解决方案 - 简单而有效:

sntc = input("Please input a sentence with no punctuation. ")
wrd = input("Please input a word from that sentence. ")
words = sntc.split()
print(words.index(wrd) + 1)

使用枚举和列表:

sntc = input("Please input a sentence with no punctuation. ")
wrd = input("Please input a word from that sentence. ")
words = sntc.split()
e = list(enumerate(sntc))
for ind, word1 in e:
    if word1 == wrd:
        print("The chosen word is in postion(s):", ind+1)

由于以下几个原因,您的代码无效:

1)如果要将函数的返回值赋给变量,请调用该函数以获取该返回值而不是函数本身:

>>> words = sntc.split
>>> words                  # the variable words now contains a function
<built-in method split of str object at 0x0243F4D0>
>>> words = sntc.split()
>>> words                  # and now a list that you want
['text', 'text', 'text']

2)你不能迭代enumerate,因为它是一个函数,而不是一个可迭代的函数 你没有将list(enumerate(sntc))分配给任何变量,我很确定你想要迭代它:

e = list(enumerate(sntc)) # now you can iterate over e
for ind, word in e:
    print(ind, word)

答案 2 :(得分:0)

如果您想要列表中元素的位置,请使用listname.index()

a = ["hello", "world"]
a.index("hello")
returns 0

答案 3 :(得分:0)

以下方法可帮助您使用.split,enumerate和list来查找句子中单词的位置。

sentence = 'I like movie'       # given sentence
sentence = sentence.split()     # spliting sentence to split
wrd = 'like'                    # a given word to find position in the sentence
[i for i, w in enumerate(sentence) if w==wrd]