【问题标题】:Word list from text file文本文件中的单词列表
【发布时间】:2013-04-09 01:05:49
【问题描述】:

我需要从一个文本文件创建一个单词列表。该列表将用于刽子手代码中,需要从列表中排除以下内容:

  1. 重复的单词
  2. 少于 5 个字母的单词
  3. 包含 'xx' 作为子字符串的单词
  4. 包含大写字母的单词

然后需要将单词列表输出到文件中,以便每个单词都出现在自己的行中。 程序还需要输出最终列表中的单词数。

这是我所拥有的,但它无法正常工作。

def MakeWordList():
    infile=open(('possible.rtf'),'r')
    whole = infile.readlines()
    infile.close()

    L=[]
    for line in whole:
        word= line.split(' ')
        if word not in L:
            L.append(word)
            if len(word) in range(5,100):
                L.append(word)
                if not word.endswith('xx'):
                    L.append(word)
                    if word == word.lower():
                        L.append(word)
    print L

MakeWordList()

【问题讨论】:

  • 怎么不能正常工作?您预计会发生什么,以及真正会发生什么?
  • 5个字母以下的单词不带走,大写字母的单词保留。

标签: python parsing


【解决方案1】:

您在这段代码中多次附加了这个词,
您实际上根本没有过滤掉单词,只是根据它们通过的if 的数量来添加不同的计时次数。

你应该合并所有if的:

if word not in L and len(word) >= 5 and not 'xx' in word and word.islower():
    L.append(word)

或者,如果您希望它更具可读性,您可以拆分它们:

    if word not in L and len(word) >= 5:
        if not 'xx' in word and word.islower():
            L.append(word)

但不要在每个之后追加。

【讨论】:

  • 应该是word.endswith('xx'),而不是'xx' in word
  • @twasbrillig 然后"abxxcd" 也会匹配。这不是他想要的。
  • 让我澄清一下。而不是not word.endswith('xx'),它应该是not 'xx' in word。否则"abxxcd" 也会匹配,这不是他想要的。
  • @twasbrillig 我明白了,我从 OP 的代码中假设他只希望结尾有 'xx'。从他的描述来看,这似乎是不正确的。不错的选择。
【解决方案2】:

想一想:在您的嵌套 if 语句中,任何不在列表中的单词都会在您的第一行出现。然后,如果它是 5 个或更多字符,它将被添加再次(我打赌),等等。您需要重新考虑 if 语句中的逻辑。

【讨论】:

    【解决方案3】:

    改进的代码:

    def MakeWordList():
        with open('possible.rtf','r') as f:
            data = f.read()
        return set([word for word in data if len(word) >= 5 and word.islower() and not 'xx' in word])
    

    set(_iterable_) 返回一个没有重复的集合类型对象(所有set 项必须是唯一的)。 [word for word...] 是一种列表推导式,它是一种创建简单列表的更短方式。您可以遍历“数据”中的每个单词(假设每个单词都在单独的行上)。 if len(word) >= 5 and word.islower() and not 'xx' in word 满足最后三个要求(必须超过5个字母,只有小写字母,不能包含'xx')。

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 2014-11-20
      • 2023-03-26
      相关资源
      最近更新 更多