【问题标题】:Creating a dictionary using python and a .txt file使用 python 和 .txt 文件创建字典
【发布时间】: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


【解决方案1】:

这是一个返回第一个定义的函数:

def lookup(word):
    word_upper = word.upper()
    found_word = False
    found_def = False
    defn = ''
    with open('dict.txt', 'r') as file:
        for line in file:
            l = line.strip()
            if not found_word and l == word_upper:
                found_word = True
            elif found_word and not found_def and l.startswith("Defn:"):
                found_def = True
                defn = l[6:]
            elif found_def and l != '':
                defn += ' ' + l
            elif found_def and l == '':
                return defn
    return False

print lookup('hallucination')

说明:我们必须考虑四种不同的情况。

  • 我们还没有找到这个词。我们必须将当前行与我们要查找的大写单词进行比较。如果它们相等,我们就找到了这个词。
  • 我们找到了这个词,但还没有找到定义的开头。因此,我们必须寻找以Defn: 开头的行。如果找到了,我们将这一行添加到定义中(不包括 Defn: 的六个字符。
  • 我们已经找到了定义的开始。在这种情况下,我们只需将这一行添加到定义中。
  • 我们已经找到定义的开始,当前行是空的。定义完成,我们返回定义。

如果我们什么也没找到,我们返回 False。

注意:有某些条目,例如CRANE,有多个定义。上面的代码无法处理。它只会返回第一个定义。然而,考虑到文件的格式,编写一个完美的解决方案远非易事。

【讨论】:

    【解决方案2】:

    你可以分段落,使用搜索词的索引,在后面找到第一个Defn段落:

    def find_def(f,word):
        import re
        with open(f) as f:
            lines = f.read() 
            try:
                start = lines.index("{}\r\n".format(word)) # find where our search word is
            except ValueError: 
                return "Cannot find search term" 
            paras = re.split("\s+\r\n",lines[start:],10) # split into paragraphs using maxsplit = 10 as there are no grouping of paras longer in the definitions
            for para in paras:
                if para.startswith("Defn:"): # if para startswith Defn: we have what we need
                    return para # return the  para
    
    print(find_def("in.txt","HALLUCINATION"))
    

    使用整个文件返回:

    In [5]: print find_def("gutt.txt","VACCINATOR")
    Defn: One who, or that which, vaccinates.
    
    In [6]: print find_def("gutt.txt","HALLUCINATION")
    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.
    

    略短的版本:

    def find_def(f,word):
        import re
        with open(f) as f:
            lines = f.read()
            try:
                start = lines.index("{}\r\n".format(word))
            except ValueError:
                return "Cannot find search term"
            defn = lines[start:].index("Defn:")
            return re.split("\s+\r\n",lines[start+defn:],1)[0]
    

    【讨论】:

      【解决方案3】:

      here 我学到了一种简单的方法来处理内存映射文件并将它们当作字符串一样使用。然后,您可以使用类似的方法来获取术语的第一个定义。

      def lookup(search):
          term = search.upper()
          f = open('webster.txt')
          s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
          index = s.find('\r\n\r\n' + term + '\r\n')
          if index == -1:
              return None
          definition = s.find('Defn:', index) + len('Defn:') + 1
          endline = s.find('\r\n\r\n', definition)
          return s[definition:endline]
      
      print lookup('hallucination')
      print lookup('hallucinate')
      

      假设:

      • 每个术语至少有一个定义
      • 如果有多个,则只返回第一个

      【讨论】:

      • 我必须阅读大量内容才能理解它,但它看起来是一个很棒的方法。有没有办法使查找“唯一”?这意味着他们找到了准确的词,例如 lookup("vaccination") 返回 antivaccination 的定义
      • 假设所有术语都在双 \r\n 之后,我们可以找到具体术语。查看我的编辑。
      • 这也会找到部分匹配项
      • @PadraicCunningham 即使有我之前所做的更新?我正在明确搜索一个由双换行符和换行符包围的术语,即单独在一行中。也许我在这里缺少一些东西。你能给我举个例子吗?我尝试了 vaccinationantivaccination 并且它起作用了。尝试使用 gate 并且它也有效。
      • lookup('halluc') Out[27]: "e Project Gutenberg EBook of Webster's Unabridged Dictionary, by Various"
      猜你喜欢
      • 2021-05-10
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      相关资源
      最近更新 更多