2017-04-06 58 views
-1
myFile = open("task3.txt","r") 
myList = myFile.readlines() 
word = myList[0].split(' ') 
position = [0] 

for count, i in enumerate(word): 
    if word.count(i) < 2: 
     position.append(count+1) 
    else: 
     position.append(word.index(i)+1) 

position.remove(0) 
print(position) 
recreate= [] 
for count in position: 
    recreate.append(word[count-1]) 
    print(recreate) 
    with open ("test.txt","w") as file: 
     file.write(" ".join(recreate)) 

这里我的代码应该拆分读取文件到单词和位置,并利用这些来做到这一点正确地重新句话在新file.It,但是当我打印的位置,他们都错了:当我的代码输出时,为什么位置错误?

这是正确的位置:[1,2,3,4,5,5,4,3,6,7,8]

task3.txt =一,二,三,四,五,五,四,三,二和一。

,这是被印刷的内容:[1,2,3,4,5,5,4,3,9,10,11]

的test.txt =一个,两个,三个,四个,五,五,四,三,二和一。

谢谢。

+0

为什么是正确的输出?什么是输入? –

+0

由于位置对应于列表中每个单词的索引:“two = index(8)+ 1 = 9”和“index(9)+ 1 = 10”,所以位置看起来不错,一个指数=(10)+ 1 = 11'。不知道为什么'6,7,8'是正确的位置。 – davedwards

回答

0

您曾经期待的位置是指某个列表中的所有单词都是唯一的,但您从未创建过这样的列表。而是指您希望重复的原始列表。因此,这些数字当然跳过跳过现有的重复。

我觉得你的意思,使独特标记的新列表,就像这样:

data = "one, two, three, four, five, five, four, three, two and one." 

tokens = [] 
position = [] 
for word in data.split(' '): 
    if word in tokens: 
     position.append(tokens.index(word)) 
    else: 
     position.append(len(tokens)) 
     tokens.append(word) 

print("Here are the unique words: ") 
print(tokens) 

def inc(n): 
    return n+1 
print("Here is a list of tokens in the input, where the indexes are changed to one-based indexing:") 
print(map(inc, position)) 

recreate= [] 
for token_index in position: 
    recreate.append(tokens[token_index]) 

print("Before:" + data) 
print("After :" + " ".join(recreate)) 

输出:

Here are the unique tokens: 
['one,', 'two,', 'three,', 'four,', 'five,', 'two', 'and', 'one.'] 
Here is a list of tokens in the input, where the indexes are changed to one-based indexing: 
[1, 2, 3, 4, 5, 5, 4, 3, 6, 7, 8] 
Before:one, two, three, four, five, five, four, three, two and one. 
After :one, two, three, four, five, five, four, three, two and one. 
相关问题