【问题标题】:Call multiple functions inside list comprehension在列表理解中调用多个函数
【发布时间】:2017-03-10 09:55:36
【问题描述】:

我正在尝试导入一个文本文件并将文本返回到每个单词的字符串列表中,同时还返回小写字母且没有标点符号。

我创建了以下代码,但这不会将每个单词拆分成一个字符串。也可以在理解中添加.lower() 吗?

def read_words(words_file):
    """Turns file into a list of strings, lower case, and no punctuation"""
    return [word for line in open(words_file, 'r') for word in line.split(string.punctuation)]

【问题讨论】:

  • 请添加示例输入、您想要作为输出获得的内容以及您获得的实际输出。
  • 为什么流程需要是列表推导式?
  • 这不需要是一种理解。只是认为这将是最少的代码

标签: python list list-comprehension


【解决方案1】:

是的,您可以将.lower 添加到理解中。它可能应该发生在word。此外,由于string.punctuation,以下代码可能不会拆分每个单词。如果您只是想在空白处拆分,调用 .split() 不带参数就足够了。

【讨论】:

    【解决方案2】:

    这是一个列表推导,应该可以满足您的所有需求:

    [word.translate(None, string.punctuation).lower() for line in open(words_file) for word in line.split()]
    

    您需要在空格(默认)上拆分以分隔单词。然后您可以转换每个生成的字符串以删除标点符号并将其变为小写。

    【讨论】:

      【解决方案3】:
      import string
      def read_words(words_file):
          """Turns file into a list of strings, lower case, and no punctuation"""
          with open(words_file, 'r') as f:
              lowered_text = f.read().lower()
          return ["".join(char for char in word if char not in string.punctuation) for word in lowered_text.split()]
      

      【讨论】:

        【解决方案4】:

        使用mapping to translate the words 并在生成器函数中使用它。

        import string
        def words(filepath):
            '''Yield words from filepath with punctuation and whitespace removed.'''
        
            # map uppercase to lowercase and punctuation/whitespace to an empty string
            t = str.maketrans(string.ascii_uppercase,
                              string.ascii_lowercase,
                              string.punctuation + string.whitespace)
        
            with open(filepath) as f:
                for line in f:
                    for word in line.strip().split():
                        word = word.translate(t)
                        # don't yield empty strings
                        if word:
                            yield word
        

        用法

        for word in words('foo.txt'):
            print(word)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-24
          • 2019-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多