2017-04-18 56 views
1

我想刪除我的輸出的空格,並且嘗試過單詞= [x的單詞x.strip('')],但它根本不起作用。從變量和空格打開文件

另外,我試圖讓它打開比文件data1.txt多。我試圖將它分配給我的輸入,但它永遠不會識別它,因爲它是一個字符串時顯示的括號,我想不確定是否是原因。

Exemple of output: 
anana : 12 
Orange:24 
Patate: 21 


def ligne(texte): 
    with open(texte) as ouvrir: 
     lecture = ouvrir.readlines() 
     words = [x.split(":")[0].strip() for x in [line.strip() for line in lecture]] 
     words = [x for x in words if len(x) > 1] 
     return lecture 
    return "Le fichier {} n'existe pas.".format(texte) 

def main(): 
    while True: 
     entree = sys.argv[1:] 
     choix = str(entree) 
     texte = "data2.txt" 
     if texte in choix: 
      message4 = sorted(ligne(texte)) 
      for i in message4: 
       print(i) 
      break 
     else: 
      print("Il faut préciser le nom du fichier à traiter") 
      break 
+0

text.split()可能會有幫助,它分裂一個海峽行成使用空格作爲分隔符 – freude

回答

2

你回來return lecture,但你改變words,也可以更改代碼splitstrip您輸入線,像這樣:

def ligne(texte): 
    with open(texte) as ouvrir: 
     lecture = ouvrir.readlines() 
     words = [':'.join([x.strip() for x in line.split(':')]) for line in lecture] 
     words = [x for x in words if len(x) > 1] 
     return words 
    return "Le fichier {} n'existe pas.".format(texte) 

如果你要撥打多個文件,你可以這樣做:

def main(): 
    entree = sys.argv[1:] 
    for item in entree: 
     message4 = sorted(ligne(item)) 
     for i in message4: 
      print(i) 

並運行代碼絲毫文件作爲參數:

python your_code.py first_file.txt secend_file.txt ... 
+0

我的話lookds這樣patate的單詞列表:21我沒有看到:21時,我這樣做 – Isen

+0

請給我一個簡單的輸入和您的預期輸出 – RaminNietzsche

+0

我編輯了我的問題。而且我的輸入是我想要打開的文件名。在這種情況下,它是data1.txt,但我可以輸入data2.txt或data3.txt也 – Isen