2017-06-10 69 views
-2

社區,加入兩個子列表

我努力追加我從文本文件中提取的兩個子列表(p和t)。代碼應該可以「打印(p,t)」,但後來的append命令不起作用(我也嘗試了output.extend([p,t]))。這些列表包含: p =代詞(由testpersons發音) t = testpersons(縮寫爲VP +數字) 不僅如此,在當前代碼中,不幸的是沒有工作。 我也得到一個縮進錯誤,我的同事使用相同的代碼工作得不到。

謝謝!

import re 

    with open (r'./Transliteration_Task1_DE.txt', 'r')as file: 

     pro=["ich", "mir", "mich", "wir", "uns", "du", "dir", "dich"] 
     t="" #variable for testpersons 
     output=list() 
     for line in file: 
      words=list() 
      words=line.split(" ") 
      #print(words) 
      if re.match(r'.*VP.*', line): 
       t=line 
       words=line.split(" ") 
       #print(words) 
      for w in words: 
       #print(w) 
       for p in pro: 
        if p == w: 
         print(p, t) 
         output.append([p,t]) 
     for o in output: 
      print(output) #output should be a list with sublists (testpersons and pronouns) 
+0

縮進錯誤通常是混合了製表符/空格。你使用了哪些文本編輯器? 你真的只需要做一個循環 - 你可以改變'w爲單詞:對於專業版中的p:if p == w:'類似於'for w的單詞:if w in pro:' –

+2

Please give an你期待的例子 –

+0

@Kind陌生人謝謝!我正在使用Notepad ++。我想得到一個輸出結果:參與者,職業發生的線。例如。 VP1,「Ich lege die Banane」; – user3429227

回答

2

您的代碼可以簡化爲:

pronouns = ["ich", "mir", "mich", "wir", "uns", "du", "dir", "dich"] 
output = [] 

with open (r'./Transliteration_Task1_DE.txt', 'r') as file: 
    for line_number, line in enumerate(file): 
     words = line.split() # Split the line on whitespaces such that words contains a list of words from the line. 

     if "VP" in line: # Only do something if the line contains "VP" - you don't need a regular expression. 
      for pronoun in pronouns: # Search all pronouns 
       if pronoun in words: # If the pronoun is in the list of words, append it to the output 
        print(pronoun, line_number, line) 
        output.append([pronoun, line_number, line]) 

for o in output: 
    print(o) 

要得到行號,你可以enumerate文件句柄。

要查看該行是否包含字符串VP,使用in運算符有更多pythonic方法。

對於第二個嵌套for循環類似:只需使用in來查看代詞是否包含在單詞列表中。

此外,它有助於提供更多可讀的變量名稱。單字符名稱通常會令人困惑並且很難閱讀。

另外,請記住,您的輸入行可能包含您可能需要刪除的標點符號或大寫/小寫字母組合。如果您希望不區分大小寫,則需要將所有字都設置爲小寫(請參見strlower功能)。

1

如果這是你想要做什麼,你可以使用+運營商加入兩個列表:

>>> p = [0, 1] 
>>> q = [2, 3] 
>>> p + q 
[0, 1, 2, 3] 

使用*(星號),一元運算符解壓元素:

>>> [*p, *q] 
[0, 1, 2, 3] 

並使用.extend()列表方法:

>>> p.extend(q) 
>>> print(p) 
[0, 1, 2, 3]