【问题标题】:Most pythonic way to create a list of strings from lines in a text file? [duplicate]从文本文件中的行创建字符串列表的最pythonic方法? [复制]
【发布时间】:2019-11-29 20:02:43
【问题描述】:

从文本文件lines_of_words.txt

第一
第二
第三个

必须创建一个字符串形式的单词列表,即

list_of_strings = ['first', 'second', 'third']

这似乎是一个极其微不足道的功能,但我找不到简洁的解决方案。我的尝试要么太麻烦要么产生错误的输出,例如

['f', 'i', 'r', 's', 't', '\n', 's', 'e', 'c', 'o', 'n', 'd', '\n', 't', 'h', 'i', 'r', 'd', '\n']

first
second
third

完成这项工作的最 Pythonic 函数是什么?到目前为止,我的出发点是

with open('list_of_words', 'r') as list_of_words:
    # Do something...
print(list_of_strings)

【问题讨论】:

  • list_of_strings = list_of_words.readlines()。要去除换行符\n,请使用list(map(str.strip, list_of_words.readlines()))
  • @abdusco:这将在每行末尾包含'\n' 字符。
  • 最pythonic的方法是不将整个文件读入列表,而是逐行处理文件。

标签: python string list text-files


【解决方案1】:

您可以在文件处理程序上使用list(..)。由于字符串将包含一个新行,您可能希望使用 str.rstrip 删除右侧的 '\n' 部分:

with open('list_of_words', 'r') as f:
    list_of_strings = list(map(str.rstrip, f))
print(list_of_strings)

【讨论】:

  • 谢谢,这太完美了。
  • 一个问题:str.rstrip 中的str 指向哪里,即解释器如何知道str 指的是list_of_strings 中的各个字符串?这很好用(而例如map(rstrip(), f) 没有),只是str 似乎出乎意料。
  • @david: str 指的是str 类。如果它在类级别定义的方法(并且它不是静态方法或类方法),那么str.foo(x)x.foo() 相同,因为x 是一个字符串。
  • 这种行为有技术名称吗?
  • @david:在数学中,这将是“部分应用”。例如stackoverflow.com/q/2709821/67579 这里解释的行为。
【解决方案2】:
with open('list_of_words', 'r') as f_in:
    data = [*map(str.strip, f_in)]

print(data)

打印:

['first', 'second', 'third']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 2013-01-26
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多