簡體   English   中英

Python:如何正確使用readline()和readlines()

[英]Python: How to properly use readline() and readlines()

我已經按照Gödel,Escher和Bach提供的圖表,構建了一個Python腳本,使用來自Princeton English Wordnet的數據隨機創建句子。 調用python GEB.py會產生英語無意義的句子列表,例如:

復蘇的麻醉費用。 苔蘚植物指甲。 第四十號桃子。 星空皮。 經過重新包裝的要求使翻譯成a_d_d的長袍的面粉穿透了蘋果樹。 在金槍魚旁邊的一具小葉貨輪。

並將它們保存到gibberish.txt。 這個腳本工作正常。

另一個腳本( translator.py )使用gibberish.txt,並通過py-googletrans Python模塊嘗試將這些隨機句子翻譯成葡萄牙語:

from googletrans import Translator
import json

tradutor = Translator()

with open('data.json') as dataFile:
    data = json.load(dataFile)


def buscaLocal(keyword):
    if keyword in data:
        print(keyword + data[keyword])
    else:
        buscaAPI(keyword)


def buscaAPI(keyword):
    result = tradutor.translate(keyword, dest="pt")
    data.update({keyword: result.text})

    with open('data.json', 'w') as fp:
        json.dump(data, fp)

    print(keyword + result.text)


keyword = open('/home/user/gibberish.txt', 'r').readline()
buscaLocal(keyword)

當前,第二個腳本僅輸出gibberish.txt中第一句的翻譯。 就像是:

復蘇的麻醉費用。 aumento de custosinestético。

我嘗試使用readlines()代替readline() ,但是出現以下錯誤:

Traceback (most recent call last):
  File "main.py", line 28, in <module>
    buscaLocal(keyword)
  File "main.py", line 11, in buscaLocal
    if keyword in data:
TypeError: unhashable type: 'list'

我在這里已經閱讀了有關此錯誤的類似問題,但是我不清楚我應該使用什么來讀取gibberish.txt中包含的整個句子列表(新句子從新行開始)。

如何閱讀gibberish.txt中包含的整個句子列表? 我應該如何修改translator.py中的代碼以實現該目標? 很抱歉,如果這個問題有點令人困惑,我可以根據需要進行編輯,我是Python新手,如果有人可以幫助我,我將不勝感激。

如果使用readline()函數,則必須記住該函數僅返回一行,因此必須使用循環來遍歷文本文件中的所有行。 如果使用readlines() ,則此函數會一次讀取完整文件,但返回列表中的每一行。 列表數據類型不可散列,並且不能用作dict對象中的鍵,這就是為什么if keyword in data: line會發出此錯誤的原因,因為此處的keyword是所有行的列表。 一個簡單的for循環將解決此問題。

text_lines = open('/home/user/gibberish.txt', 'r').readlines()
for line in text_lines:
     buscaLocal(line)

此循環將遍歷列表中的所有行,並且訪問dict會出錯,因為key元素將是一個字符串。

讓我們從您對文件對象所做的事情開始。 您打開一個文件,從中獲得一行,然后再關閉它。 更好的方法是處理整個文件,然后將其關閉。 通常使用with塊完成此操作,即使發生錯誤,該塊也會關閉文件:

with open('gibberish.txt') as f:
    # do stuff to f

除了物質上的好處外,這將使界面更清晰,因為f不再是一次性的對象。 您可以使用三個簡單的選項來處理整個文件:

  1. 在循環中使用readline ,因為它一次只能讀取一行。 您將必須手動剝離換行符,並在出現''時終止循環:

     while True: line = f.readline() if not line: break keyword = line.rstrip() buscaLocal(keyword) 

    此循環可以采用多種形式,此處顯示其中一種形式。

  2. 使用readlines一次將文件中的所有行讀入字符串列表:

     for line in f.readlines(): keyword = line.rstrip() buscaLocal(keyword) 

    這比以前的選項要干凈得多,因為您不需要手動檢查循環終止,但是它的缺點是一次加載整個文件,而readline循環則沒有。

    這將我們帶到第三個選項。

  3. Python文件是可迭代的對象。 您可以通過節省readline來保持readlines方法的整潔度:

     for line in f: buscaLocal(line.rstrip()) 

    可以使用readlinenext的更多神秘形式來模擬這種方法,以創建類似的迭代器:

     for line in next(f.readline, ''): buscaLocal(line.rstrip()) 

附帶說明一下,我將對您的功能進行一些修改:

def buscaLocal(keyword):
    if keyword not in data:
        buscaAPI(keyword)
    print(keyword + data[keyword])

def buscaAPI(keyword):
    # Make your function do one thing. In this case, do a lookup.
    # Printing is not the task for this function.
    result = tradutor.translate(keyword, dest="pt")
    # No need to do a complicated update with a whole new
    # dict object when you can do a simple assignment.
    data[keyword] = result.text

...

# Avoid rewriting the file every time you get a new word.
# Do it once at the very end.
with open('data.json', 'w') as fp:
    json.dump(data, fp)

暫無
暫無

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

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