列表中的单个单词然后打印这些单词的位置

时间:2016-02-12 15:36:08

标签: python

我需要帮助一个识别句子中单个单词的程序,将它们存储在一个列表中,并将原始句子中的每个单词替换为该单词在列表中的位置。这是我到目前为止所拥有的。

例如:

'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR' COUNTRY

将重新创建为1,2,3,4,5,6,7,8,9,1,3,9,6,7,8,4,5

from collections import OrderedDict

sentence = input("Please input a sentence without punctuation").upper()

punctuation = ("`1234567890-=¬!£$%^&*()_+\|[];'#,./{}:@~<>?")

FilteredSentence = ("")

for char in sentence:
    if char not in punctuation:
        FilteredSentence = FilteredSentence+char

FilteredSentence =  FilteredSentence.split(" ")

refined = list(OrderedDict.fromkeys(FilteredSentence))

我设法识别列表中的单个单词,但是我找出了如何用单个单词的位置替换原始列表中的单词。

5 个答案:

答案 0 :(得分:10)

喜欢这个?只需进行列表理解即可获得所有单词的所有索引。

In [77]: sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"

In [78]: words = sentence.split()

In [79]: [words.index(s)+1 for s in words]
Out[79]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5]

答案 1 :(得分:4)

你也可以创建一个字典,用它们的初始位置来映射这些单词,然后用它来代替各自位置的单词。

>>> s = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY'
>>> 
>>> 
>>> l = s.split()
>>> l
['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR', 'YOU', 'ASK', 'WHAT', 'YOU', 'CAN', 'DO', 'FOR', 'YOUR', 'COUNTRY']
>>> 
>>> d = dict((s, l.index(s)+1) for s in set(l))
>>> d
{'DO': 7, 'COUNTRY': 5, 'CAN': 6, 'WHAT': 3, 'ASK': 1, 'YOUR': 4, 'NOT': 2, 'FOR': 8, 'YOU': 9}
>>> list(map(lambda s: d[s], l))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5]
>>> 

答案 2 :(得分:0)

天真的做法。

mystr = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
a = mystr.split(" ")
k = dict()
cnt = 1
b = []
for m in a:
    if m not in k:
        k[m] = str(cnt)
        cnt = cnt + 1
    b.append(k[m])
print ",".join(b)

更短的版本。

mystr = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
a = mystr.split(" ")
print ",".join([str(a.index(k)+1) for k in a])

答案 3 :(得分:0)

您可以只使用一个集合而不是OrderedDict。

refined = list(set(FilteredSentence))

比你可以在列表中检查每个单词。

index_list = []
for word in FilteredSentence:
    index_list.append(refined.index(word) +1)

index_list是您要求的结果

答案 4 :(得分:0)

只是对现有答案的改进 - 您可以使用字典理解来创建从单词到索引的查找:

>>> lookup = {w:(i+1) for i, w in list(enumerate(refined)) }

>>> lookup
{'DO': 7, 'WHAT': 3, 'FOR': 8, 'COUNTRY': 5, 'NOT': 2, 'CAN': 6,
 'ASK': 1, 'YOU': 9, 'YOUR': 4}

然后使用列表推导来生成输出索引:

>>> [lookup[w] for w in FilteredSentence]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5]