Python 卡在一个涉及列表、句子和列表中位置的程序上
所以我正在创建一个程序,识别句子中的单个单词,并打印出单词的位置。例如,应该输出句子:“我爱编码我爱的代码” “我喜欢编码 1234412“ 我可以做数字/位置,但我无法识别单个单词。你能帮我吗?你能帮我改进代码吗?谢谢 这是我的密码:Python 卡在一个涉及列表、句子和列表中位置的程序上,python,python-3.x,Python,Python 3.x,所以我正在创建一个程序,识别句子中的单个单词,并打印出单词的位置。例如,应该输出句子:“我爱编码我爱的代码” “我喜欢编码 1234412“ 我可以做数字/位置,但我无法识别单个单词。你能帮我吗?你能帮我改进代码吗?谢谢 这是我的密码: sentence = input("What is your sentence?: ") sentence = sentence.split() positions = [0] for count, i in enumerate(sentence):
sentence = input("What is your sentence?: ")
sentence = sentence.split()
positions = [0]
for count, i in enumerate(sentence):
if sentence.count(i) < 2:
positions.append(max(positions) + 1)
else:
positions.append(sentence.index(i) +1)
positions.remove(0)
file = open("positions.txt","w")
positions = " ".join(map(str, positions))
file.write(positions)
file.close()
句子=输入(“你的句子是什么?”)
句子=句子。拆分()
职位=[0]
对于计数,我在枚举(句子):
如果第(i)项小于2:
位置。追加(最大(位置)+1)
其他:
位置.附加(句子.索引(i)+1)
位置。删除(0)
文件=打开(“positions.txt”、“w”)
positions=”“.连接(映射(str,positions))
文件写入(位置)
file.close()文件
我现在意识到这个结构与@hsfzxjy编写的非常相似。但是,此代码不会引发TypeError:
from collections import OrderedDict
sentence = "I LOVE TO CODE CODE I LOVE"
positions = OrderedDict()
def get_word_index(word, index, positions):
position = positions.get(word)
if position:
return str(position)
else:
positions[word] = index
return str(index)
indices = [get_word_index(word, index, positions) for index, word in enumerate(sentence.split(), 1)]
print ' '.join(positions.keys())
# "I LOVE TO CODE"
print ' '.join(indices)
# "1 2 3 4 4 1 2"
我现在意识到这个结构与@hsfzxjy写的非常相似。但是,此代码不会引发TypeError:
from collections import OrderedDict
sentence = "I LOVE TO CODE CODE I LOVE"
positions = OrderedDict()
def get_word_index(word, index, positions):
position = positions.get(word)
if position:
return str(position)
else:
positions[word] = index
return str(index)
indices = [get_word_index(word, index, positions) for index, word in enumerate(sentence.split(), 1)]
print ' '.join(positions.keys())
# "I LOVE TO CODE"
print ' '.join(indices)
# "1 2 3 4 4 1 2"
我建议你把这个发到。我建议你把这个发到。
sentence = input("What is your sentence?: ")
words = sentence.split()
unique_words=[]
for i in words:
if i not in unique_words:
unique_words.append(i)
print unique_words
indexes=[]
for i in words:
for j in range(0,len(unique_words)):
if i==unique_words[j]:
indexes.append(j+1)
print indexes