2017-04-06 86 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. 
相關問題