从其中每个单词的位置重新创建一个句子

时间:2015-10-06 13:33:49

标签: python

我希望开发一个程序来识别句子中的单个单词,并用列表中每个单词的位置替换每个单词。

例如,这句话:

HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON

这包含11个不同的单词,我希望我的程序能够从列表中这11个单词的位置重新创建句子:

1,2,3,4,5,6,7,8,9,10,5,11,6,7

然后,我想将此新列表保存在单独的文件中。到目前为止,我只得到了这个:

#splitting my string to individual words
my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"    
splitted = my_string.split()

6 个答案:

答案 0 :(得分:1)

>>> my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"    
>>> splitted = my_string.split()
>>> order = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 11, 6, 7
>>> new_str = ' '.join(splitted[el] for el in order)
'I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP IN ME PYTHON PLEASE'
根据您的评论

更新了

您正在寻找index()方法。

my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"    
splitted = my_string.split()
test =  "I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP IN ME PYTHON PLEASE".split()
print ', '.join(str(splitted.index(el)) for el in test)

>>> 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 5, 11, 6, 7

**我们假设没有重复的单词

答案 1 :(得分:0)

my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"    
splitted = my_string.split()
d = {}
l=[]
for i,j in enumerate(splitted):
    if j in d:
        l.append(d[j])
    else:
        d[j]=i
        l.append(i)
print l

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 11, 5, 6]

答案 2 :(得分:0)

试试这个:

sentence= "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"
lst = sentence.split()
lst2= []

for i in lst:
    if i not in lst2:
        lst2.append(i)

inp = inputSentence.split()
output=[]
for i in inp:
    print lst2.index(i)+1,
    output.append(lst2.index(i)+1)

评估索引并将其存储在lst2中。您只需将输入字符串传递给inputSentence,以便能够测试此代码。

答案 3 :(得分:0)

尝试:

>>> from collections import OrderedDict
>>> my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"
>>> splitted = my_string.split()
>>> key_val = {elem : index + 1 for index, elem in enumerate(list(OrderedDict.fromkeys(splitted)))}
>>> [key_val[elem] for elem in splitted]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 11, 6, 7]

list(OrderedDict.fromkeys(splitted))创建一个仅包含splitted中唯一元素的列表 key_val是这些唯一元素的字典作为键及其索引作为值。

答案 4 :(得分:0)

benstring = input ('enter a sentence ')

print('the sentence is', benstring)

ben2string = str.split(benstring)

print('the sentence now looks like this',ben2string)

x=len(ben2string)   
for i in range(0,x):
    if x is 

答案 5 :(得分:0)

Sentence = input("Enter a sentence!")
s = Sentence.split() #Splits the numbers/words up so you can see them individually.
another = [0]

for count, i in enumerate(s):
    if s.count(i) < 2:
        another.append(max(another) + 1) #adds +1 each time a word is used, showing the position of each word.
    else:
        another.append(s.index(i) +1)

another.remove(0)

print(another) #prints the number that word is in.