简体   繁体   English

python中如何将文本转换为列表

[英]How to convert text to list in python

input=""" intro: hey,how are you i am fine intro: hey, how are you Hope you are fine """ output= [['hey,how are you i am fine'],['hey, how are you Hope you are fine']] for text in f: text = text.strip()

I would look into something like regex or just use我会研究正则表达式之类的东西或者只是使用

input.split("intro:") or input.splitlines() to generate a list of strings. input.split("intro:")input.splitlines()生成字符串列表。 That would not result in the form you have below.这不会导致您在下面的表格。 But since your question is not clear thats the best i can do.但是由于您的问题不清楚,那是我能做的最好的。

You could do this by splitting the input data by the string intro: .您可以通过按字符串intro:拆分输入数据来做到这一点。 This will give you a list of the required items.这将为您提供所需项目的列表。 You can clean this up a little more by removing the \n and leading/trailing spaces.您可以通过删除\n和前导/尾随空格来进一步清理它。

As an example:举个例子:

data = """
intro: hey,how are you
i am fine

intro:
hey, how are you
Hope you are fine
"""
only_intro = []
for intro in data.split("intro:"):
    if not intro.isspace():
        only_intro.append(intro.replace('\n', ' ').lstrip().rstrip())
print(only_intro)

which gives the following output:给出以下 output:

['hey,how are you i am fine', 'hey, how are you Hope you are fine']

We can use re.findall here in multiline mode:我们可以在这里以多行模式使用re.findall

inp = """intro: hey,how are you i am fine

intro: hey, how are you Hope you are fine"""

lines = re.findall(r'^\w+:\s*(.*)$', inp, flags=re.M)
print(lines)

This prints:这打印:

['hey,how are you i am fine', 'hey, how are you Hope you are fine']

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

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