【发布时间】:2014-10-20 17:06:54
【问题描述】:
我已经从 Project Gutenberg http://www.gutenberg.org/cache/epub/29765/pg29765.txt 下载了以下字典(它是 25 MB,所以如果你的连接速度很慢,请避免点击链接)
在文件中,我正在寻找的关键字是大写的,例如 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 继续阅读,直到它用完我想的换行符为止,但这也不包括必须阅读的最后一行。
有人可以用我可以用来解决这个问题的有用功能来增强我的能力(如果有一个最小的例子,我会很感激)。
所需输出示例:
lookup("幻觉")
out:徘徊;误入歧途;犯错;犯错; ——用于心理 过程。 [R.] 拜伦。
lookup("幻觉")
out:对没有现实的物体的感知,或对\r\n的感知 没有相应外因的感觉,由\r\n引起 紊乱或神经系统,如震颤谵妄;错觉。\r\n 幻觉总是脑错乱的证据,并且是\r\n 精神错乱的常见现象。 W.A.哈蒙德。
来自文字:
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,我不知道那个函数,我只用 Python 编写了 3 周的代码 :-) 但是感谢您向我提及它,我将不得不在谷歌上搜索它。但是访问文件不是我的问题,“阅读”它是。
-
@Beginner:OP 会询问有关获取文件的问题吗?不..
-
@RickyA :这是一个建议。因此,您会看到我发表了评论,而不是将其作为答案发布。无论如何,您的评论在任何情况下都无济于事
-
@Spaced,查看我在大写字母中看到的文件
HALLUCINATION,然后是HALLUCINATOR之前的几段,您是否想要从 HALLUCINATION 到HALLUCINATOR的所有行,但不包括HALLUCINATOR?跨度>
标签: python python-2.7