Python 在列表理解中调用多个函数

Python 在列表理解中调用多个函数,python,list,list-comprehension,Python,List,List Comprehension,我正在尝试导入一个文本文件,并将文本返回到每个单词的字符串列表中,同时还返回小写字母和无标点符号 我已经创建了以下代码,但这并没有将每个单词分割成一个字符串。也可以将.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, '

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

我已经创建了以下代码,但这并没有将每个单词分割成一个字符串。也可以将
.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)]

是的,您可以将
.lower
添加到理解中。它可能发生在
word
中。另外,由于
字符串.标点符号的缘故,下面的代码可能不会拆分每个单词。如果您只是尝试在空白处拆分,则调用
.split()
而不使用参数就足够了。

是的,您可以将
.lower
添加到理解中。它可能发生在
word
中。另外,由于
字符串.标点符号的缘故,下面的代码可能不会拆分每个单词。如果您只是尝试在空白处进行拆分,则调用
。split()
而不使用参数就足够了。

下面是一个列表理解,它可以满足您的所有要求:

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

您需要使用空格(默认值)分隔单词。然后,您可以转换每个结果字符串,以删除标点符号并使其小写。

下面是一个列表理解,它可以完成您想要的一切:

[word.translate(None, string.punctuation).lower() for line in open(words_file) for word in line.split()]
您需要使用空格(默认值)分隔单词。然后,您可以转换每个结果字符串以删除标点符号并使其小写。

使用a并在生成器函数中使用它

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
用法

使用a并在生成器功能中使用它

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
用法


请添加示例输入、您希望作为输出获得的内容以及您正在获得的实际输出。为什么该过程需要是列表理解?这不需要是理解。我想这将是最小的代码量。请添加示例输入、您希望作为输出获得的内容以及您正在获得的实际输出。为什么这个过程需要是列表理解?这不需要是理解。我只是觉得这是最少量的代码