简体   繁体   English

从列表中的字符串中提取第n行文本-Python

[英]Extract nth line of text from strings in list- Python

I have a list that consists of 149 text strings. 我有一个包含149个文本字符串的列表。 From each string, I would like to extract the 2nd and 7th lines of text. 我想从每个字符串中提取文本的第二行和第七行。 I'd like the results of each line to be put in a separate list. 我希望将每行的结果放在单独的列表中。

I've tried (just for one line): 我试过了(仅一行):

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

But I get the message "IndexError: list index out of range". 但是我收到消息“ IndexError:列表索引超出范围”。 I thought maybe I needed to do: 我以为也许我需要做:

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

But that gave me the message "AttributeError: 'list' object has no attribute 'splitlines'" 但这给了我以下消息:“ AttributeError:'list'对象没有属性'splitlines'”

I'm using Python 3.6. 我正在使用Python 3.6。 Any ideas? 有任何想法吗? Thanks for your help! 谢谢你的帮助!

string.splitlines is the correct function to split the lines of each string, and if it gives an IndexError for index 2 (note: this is the 3rd line) then that means that there are fewer than three lines. string.splitlines是用于分割每个字符串的行的正确函数,并且如果它为索引2提供IndexError (请注意:这是第三行),则意味着少于三行。 This is probably the code you're looking for: 这可能是您要查找的代码:

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM