我正在阅读一个包含文字的文件,如下所示:
stop_words = [x for x in open('stopwords.txt', 'r').read().split('\n')]
但我还需要同一列表中单词的 title() 版本。我可以使用一个列表理解来做到这一点吗?
最佳答案
在一个(嵌套的)列表理解中:
stop_words = [y for x in open('stopwords.txt', 'r').read().split('\n') for y in (x, x.title())]
编辑:您实际上不应该这样做,因为您将文件对象丢失到打开的文件并且无法关闭它。您应该使用上下文管理器:
with open('stopwords.txt', 'r') as f:
stop_words = [y for x in f.read().split('\n') for y in (x, x.title())]
关于python:使用列表理解将 str 和 str.title() 添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534375/