【问题标题】:Extract nth line of text from strings in list- Python从列表中的字符串中提取第 n 行文本 - Python
【发布时间】:2017-06-12 15:40:28
【问题描述】:

我有一个包含 149 个文本字符串的列表。从每个字符串中,我想提取第 2 行和第 7 行文本。我希望将每一行的结果放在一个单独的列表中。

我试过了(只用了一行):

text = []  
for string in list:
  x = string.splitlines()[2]
  text.append(x)

但我收到消息“IndexError:列表索引超出范围”。我想也许我需要这样做:

text = []  
for string in list:
  x = [string].splitlines()[2]
  text.append(x)

但这给了我消息“AttributeError: 'list' object has no attribute 'splitlines'”

我正在使用 Python 3.6。有任何想法吗?谢谢你的帮助!

【问题讨论】:

  • 你绝对不需要把它放在括号里,这使它成为一个列表。 string.splitlines 是正确的,显然,您在该特定条目中没有 3 行。 (不知道你的数据是什么样子的,我不能多说)
  • 如果您在第一次尝试分配 x 之前执行 print(len(string.splitlines())) 会打印什么?
  • 另外,要提取第二行,您应该使用 string.splitlines()[1] - 因为 0 是第一个元素,1 是第二个元素,依此类推。
  • @JimFasarakisHilliard 感谢您提供有关括号的说明。我不知道

标签: python python-3.x


【解决方案1】:

string.splitlines 是分割每个字符串行的正确函数,如果它为索引 2 提供 IndexError(注意:这是第 3 行),则意味着少于三行。这可能是您要查找的代码:

line2_results = []
line7_results = []
for str in list:
    lines = str.splitlines()
    if len(lines) >= 2:
        line2_results.append(lines[1])
        if len(lines) >= 7:
            line7_results.append(lines[6])

【讨论】:

  • 感谢您的帮助!是的,输入列表中有空白字符串,我现在看到这是导致错误的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多