簡體   English   中英

刪除標點符號后從文本文件中打印唯一單詞列表,並找到最長的單詞

[英]Print a list of unique words from a text file after removing punctuation, and find longest word

目標是a) 從文本文件中打印唯一單詞列表,並且b) 找到最長的單詞。

  • 我不能在這個挑戰中使用進口。

文件處理和主要功能是我想要的,但是需要清理列表。 從 output 可以看出,單詞與標點符號連接在一起,因此maxLength顯然是不正確的。

with open("doc.txt") as reader, open("unique.txt", "w") as writer:

    unwanted = "[],."
    unique = set(reader.read().split())
    unique = list(unique) 
    unique.sort(key=len)
    regex = [elem.strip(unwanted).split() for elem in unique]
    writer.write(str(regex))
    reader.close()

    maxLength = len(max(regex,key=len ))
    print(maxLength)
    res = [word for word in regex if len(word) == maxLength]
    print(res)



===========

樣本:

50 多年前開創了綜合實習年的概念 [7][8][9],超過 70% 的學生參加了實習年,是英國最高的。 [10]

這是一個使用str.translate() ) 在我們執行split()之前丟棄所有壞字符(+換行符)的解決方案。 (通常我們會使用帶有re.sub()的正則表達式,但不允許這樣做。)這使得清潔變得單行,這真的很整潔:

bad = "[],.\n"
bad_transtable = str.maketrans(bad, ' ' * len(bad))

# We can directly read and clean the entire output, without a reader object: 
cleaned_input = open('doc.txt').read().translate(bad_transtable)
#with open("doc.txt") as reader:
#    cleaned_input = reader.read().translate(bad_transtable)

# Get list of unique words, in decreasing length
unique_words = sorted(set(cleaned_input.split()), key=lambda w: -len(w))   

with open("unique.txt", "w") as writer:
    for word in unique_words:
        writer.write(f'{word}\n')

max_length = len(unique_words[0])
print ([word for word in unique_words if len(word) == max_length])

筆記:

  • 由於輸入已經 100% 清理和拆分,因此無需像 go 那樣將 append 放入列表/插入到集合中,然后必須稍后再進行一次清理。 我們可以直接創建unique_words (使用set()只保留唯一性)。 當我們這樣做時,我們不妨使用sorted(..., key=lambda w: -len(w))以遞減的長度對其進行排序。 只需要調用sort()一次。 並且沒有迭代附加到列表。
  • 因此我們保證max_length = len(unique_words[0])
  • 這種方法也將比嵌套循環for line in <lines>: for word in line.split(): ...iterative append() to wordlist
  • 無需做明確的writer/reader open()/.close() ,這就是with語句為您所做的。 (當異常發生時處理 IO 也更優雅。)
  • 您還可以在 writer 循環中合並 max_length 單詞的打印。 但將它們分開是更簡潔的代碼。
  • 請注意,當我們write() output 行時,我們使用f 字符串格式f'{word}\n'來添加換行符
  • 在 Python 中,我們使用 lower_case_with_underscores 作為變量名,因此max_length不是maxLength PEP8
  • 實際上,在這里,我們並不嚴格需要作者的 with 語句,如果我們要做的只是在一個 go 中使用open('doc.txt').read()將其全部內容啜飲。 (這對於大文件是不可擴展的,您必須以塊或 n 行的形式讀取)。
  • str.maketrans()是內置的,但如果您的老師反對模塊引用,您也可以在綁定字符串上調用它,例如' '.maketrans()
  • str.maketrans()真的是回到我們只有 95 個可打印 ASCII 字符的日子,而不是 Unicode。 仍然適用於 Unicode ,但構建和使用巨大的翻譯字典很煩人,並且使用 memory,Unicode 上的正則表達式更容易,您可以定義整個字符類。

如果您還不知道str.translate()替代解決方案

dirty_input = open('doc.txt').read()
cleaned_input = dirty_input
# If you can't use either 're.sub()' or 'str.translate()', have to manually
# str.replace() each bad char one-by-one (or else use a method like str.isalpha())
for bad_char in bad:
    cleaned_input = cleaned_input.replace(bad_char, ' ')

而且,如果您想成為可笑的極簡主義者,則可以將整個 output 文件寫在一行中,並帶有列表理解。 不要這樣做,調試會很糟糕,例如,如果您無法打開/寫入/覆蓋 output 文件,或者出現 IOError,或者 unique_words 不是列表等:

open("unique.txt", "w").writelines([f'{word}\n' for word in unique_words])

這是一個解決方案。 訣竅是使用 python str 方法.isalpha()過濾非字母數字。

with open("unique.txt", "w") as writer:
    with open("doc.txt") as reader:
        cleaned_words = []
        for line in reader.readlines():
            for word in line.split():
                cleaned_word = ''.join([c for c in word if c.isalpha()])
                if len(cleaned_word):
                    cleaned_words.append(cleaned_word)

        # print unique words
        unique_words = set(cleaned_words)
        print(unique_words)

        # write words to file? depends what you need here
        for word in unique_words:
            writer.write(str(word))
            writer.write('\n')

        # print length of longest
        print(len(sorted(unique_words, key=len, reverse=True)[0]))

這是另一個沒有任何 function 的解決方案。

bad = '`~@#$%^&*()-_=+[]{}\|;\':\".>?<,/?'

clean = ' '
for i in a:
    if i not in bad:
        clean += i
    else:
        clean += ' '

cleans = [i for i in clean.split(' ') if len(i)]

clean_uniq = list(set(cleans))

clean_uniq.sort(key=len)

print(clean_uniq)
print(len(clean_uniq[-1]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM