在python中,如何从文件中读取行并存储在变量中-按空间分割

在python中,如何从文件中读取行并存储在变量中-按空间分割,python,Python,我有一个包含以下格式信息的文件 文件:messages.txt John Jack'这是第一条未读的消息' John Jess“这是第二条消息”未读 凯特·玛丽“这是另一条信息”未读 .... 我想读每一行,并且 var[0]=John var[1]=Jack var[2]='this is the first message' var[3]=unread 我使用了.S拆除器,但是它拆分的问题也是我认为是字符串的消息。 var= line.strip().split() if var[

我有一个包含以下格式信息的文件 文件:messages.txt

John Jack'这是第一条未读的消息'
John Jess“这是第二条消息”未读
凯特·玛丽“这是另一条信息”未读
....
我想读每一行,并且

var[0]=John 
var[1]=Jack 
var[2]='this is the first message' 
var[3]=unread

我使用了.S拆除器,但是它拆分的问题也是我认为是字符串

的消息。
var= line.strip().split()
if var[3]=='unread'
不幸的是,python还计算消息中的空格。
如何做到这一点?

我会使用regex查找并删除
“这是第一条消息”
(文件中有引号,对吗?)

您可以使用
split()
函数的参数,并使用
split()
rsplit()
,前提是数据采用您在问题中发布的格式:

with open('messages.txt', 'r') as f:
    for line in f:
        line = line.strip()
        fname, lname, lst = line.split(maxsplit=2)     
        lst = lst.rsplit(maxsplit=1)
        print(fname, lname, lst[0], lst[1])
输出:

John Jack 'this is the first message' unread
John Jess 'this is the second message' unread

假设您的.txt文件电子邮件正文被单引号包围,您可以使用如下内容:

with open('messages.txt', "r") as file:
    for line in file:
        # Split line into array
        split_line = line.split("'")
        # Assign each index to a new variable and strip whitespace
        name = split_line[0].strip()
        message = split_line[1].strip()
        status = split_line[2].strip()

它将根据单引号拆分字符串行,并将数据放入数组中

  • 第一索引名
  • 第二个索引-消息
  • 第三项指标——地位

如果需要将名字和姓氏作为单独的变量,则可以根据名称的空格来拆分名称。

您只需使用
csv.reader
类将文本文件作为csv读取即可。对于读取器的
方言
属性,可以将撇号设置为
quotechar
,将空格设置为
分隔符
,库将为您处理一切。这允许您使用撇号在其他列上禁用按空格拆分,例如,如果您的电子邮件发件人在其
fname
/
lname
字段中有名字和中间名(请参见下面示例中的最后一行)

假设您有以下
emails.txt

John Jack'这是第一条未读的消息'
John Jess“这是第二条消息”未读
凯特·玛丽“这是另一条信息”未读
“马丁·路德”“小金”“这是最后一条信息”阅读
这将为您提供两行:

['John', 'Jack', 'this is the first message', 'unread']
['John', 'Jess', 'this is the second message', 'unread']
['Kate', 'Mary', 'this is the another message', 'unread']
['Martin Luther', 'King, Jr.', 'this is the last message', 'read']

行的消息部分是否总是用单引号括起来?您需要向我们展示(1)读取文件并解析数据的代码,(2)输入数据,(3)实际输出数据,以及(4)所需的输出。Does line.split();第[0]行、[1]行、[1:-1]行、[-1]行适合您?是的,它将用单引号引起来。消息也可能有自己的单引号。例如“这是一条“诈骗”消息”。下面给出的maxsplit工作正常,谢谢奎师那!当我阅读这些信息时,有没有简单的方法在文件中用新值替换lst[1]呢?例如,在一行中,如果1st[1]='unread',则使用'read'更新该行,保持其余内容不变。如果您是指文件的原始内容,则需要创建字符串对象并写回文件。
import csv

with open('emails.txt', 'r') as f:
    dialect = csv.excel()
    dialect.delimiter = ' '
    dialect.quotechar = "'"
    dialect.quoting = csv.QUOTE_MINIMAL
    reader = csv.reader(f, dialect)
    for row in reader:
        print(row)
['John', 'Jack', 'this is the first message', 'unread']
['John', 'Jess', 'this is the second message', 'unread']
['Kate', 'Mary', 'this is the another message', 'unread']
['Martin Luther', 'King, Jr.', 'this is the last message', 'read']