我已经下载了以下词典从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