我已經下載了以下詞典從Project Gutenberg的創建字典http://www.gutenberg.org/cache/epub/29765/pg29765.txt(這是25 MB,所以如果你是一個緩慢的連接避免點擊鏈接)使用Python和.txt文件
在文件我正在尋找的關鍵詞是大寫,例如HALLUCINATION,然後在字典中有一些專門用於發音的行,這些行對我來說已經過時了。
我想提取的是定義,用「Defn」表示,然後打印行。我已經想出了這個相當醜陋的'解決方案'
def lookup(search):
find = search.upper() # transforms our search parameter all upper letters
output = [] # empty dummy list
infile = open('webster.txt', 'r') # opening the webster file for reading
for line in infile:
for part in line.split():
if (find == part):
for line in infile:
if (line.find("Defn:") == 0): # ugly I know, but my only guess so far
output.append(line[6:])
print output # uncertain about how to proceed
break
現在這當然只打印「Defn:」後面的第一行。在Python中處理.txt文件時,我是新手,因此對於如何進行操作一無所知。我確實讀過一個元組中的行,並注意到有特殊的新行字符。
所以我想以某種方式告訴Python繼續閱讀,直到它用完我想的新行字符,但也不計算最後一行必須閱讀。
有人可以請提高我有用的功能,我可能可以用來解決這個問題(與一個最小的例子,將不勝感激)。期望的輸出的
例:
查找( 「幻覺」)
出:向漂移;誤入歧途;犯錯;失誤 - 使用精神 進程。 [R.]拜倫。
查找( 「幻覺」)
出:其不具有現實,或對象的感知\ r \ n 感覺不具有相應的外部原因,從\ r \ n 紊亂所引起的或神經系統,如deli妄的震顫;妄想。\ r \ n 幻覺總是大腦混亂的證據,並且是精神錯亂的常見現象。 W. A. Hammond。
從文本:
HALLUCINATE
Hal*lu"ci*nate, v. i. Etym: [L. hallucinatus, alucinatus, p. p. of
hallucinari, alucinari, to wander in mind, talk idly, dream.]
Defn: To wander; to go astray; to err; to blunder; -- used of mental
processes. [R.] Byron.
HALLUCINATION
Hal*lu`ci*na"tion, n. Etym: [L. hallucinatio cf. F. hallucination.]
1. The act of hallucinating; a wandering of the mind; error; mistake;
a blunder.
This must have been the hallucination of the transcriber. Addison.
2. (Med.)
Defn: The perception of objects which have no reality, or of
sensations which have no corresponding external cause, arising from
disorder or the nervous system, as in delirium tremens; delusion.
Hallucinations are always evidence of cerebral derangement and are
common phenomena of insanity. W. A. Hammond.
HALLUCINATOR
Hal*lu"ci*na`tor, n. Etym: [L.]
爲什麼不使用'urllib'訪問該文件? – Beginner 2014-10-20 17:12:23
@Beginner,我不知道這個函數,我只用了3周的代碼就可以在Python中使用:-)但是感謝你提及它,我將不得不穀歌它。但是訪問這個文件並不是我的問題,'閱讀'它是。 – Spaced 2014-10-20 17:13:37
@Beginner:OP是否詢問獲取文件?沒有.. – RickyA 2014-10-20 17:13:44