2016-08-11 13 views
0

我真的很新的python,現在我有一個錯誤,不知道爲什麼我得到這個錯誤。lambda和字母數字單詞的Python錯誤

我有3個單詞列表。這些列表包含單詞數字,文字和字母數字單詞。這些列表保存在一個txt文件中。每個文件可以包含來自其他列表或新單詞的單詞。

現在我想比較這些列表,並將沒有重複的所有單詞複製到新列表中。所以我有一個大名單,包含所有的單詞,但沒有重複。

這是我的腳本:

file_a = raw_input("File 1?: ") 
file_b = raw_input("File 2?: ") 
file_c = raw_input("File_3?: ") 
file_new = raw_input("Neue Datei: ") 

def compare_files(): 

    with open(file_a, 'r') as a: 
     with open(file_b, 'r') as b: 
      with open(file_c, 'r') as c: 
       with open(file_new, 'w') as new: 
        difference = set(a).symmetric_difference(b).symmetric_difference(c) 
        difference.discard('\n') 
        sortiert = sorted(difference, key=lambda item: (int(item.partition(' ')[0]) 
                    if item[0].isdigit() else float('inf'), item)) 

        for line in sortiert: 
         new.write(line) 

k = compare_files() 

當我運行該腳本,我得到了以下錯誤消息:

Traceback (most recent call last): 
    File "TestProject1.py", line 19, in <module> 
    k = compare_files() 
    File "TestProject1.py", line 13, in compare_files 
    sortiert = sorted(difference, key=lambda item: (int(item.partition(' ')[0]) 
    File "TestProject1.py", line 14, in <lambda> 
    if item[0].isdigit() else float('inf'), item)) 
ValueError: invalid literal for int() with base 10: '12234thl\n' 

任何一個想法什麼的什麼是錯的,我的腳本?

謝謝您的幫助:)

+2

那麼,你認爲「12234thl \ n''是多少? –

+0

你想要達到的排序順序是什麼? –

+0

你只是試圖把一個字母數字字符串變成一個整數 – Anonymous

回答

0

partition' '或任何其他字符串爲此事,除非你知道緊隨數字的字符不會提取字符串的數字部分;非常不可能。

您可以改爲使用正則表達式來提取字符串的前導數字部分:

import re 

p = re.compile(r'^\d+') 

def compare_files(): 

    with open(file_a, 'r') as a, open(file_b, 'r') as b, \ 
     open(file_c, 'r') as c, open(file_new, 'w') as new: 
     difference = set(a).symmetric_difference(b).symmetric_difference(c) 
     difference.discard('\n') 
     sortiert = sorted(difference, 
          key=lambda item: (int(p.match(item).group(0)) \ 
              if item[0].isdigit() \ 
              else float('inf'), item)) 

     for line in sortiert: 
      new.write(line) 

模式'^\d+'應匹配從字符串的開始所有的數字,然後p.match(item).group(0)返回數字作爲一個字符串然後可以將鑄造成爲整數。

+0

我實施了您的更改,現在其工作完美無缺。謝謝 :) – meGnom