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



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

John Jack 'this is the first message' unread
John Jess 'this is the second message' unread
Kate Mary 'this is the another message' unread
....

我想阅读每一行并进行

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

我使用了.split,但它也拆分了我认为是一个字符串的消息

var= line.strip().split()
if var[3]=='unread'

不幸的是,python还会计算消息中的空格。如何做到这一点?

您可以使用split()函数的maxsplit参数,并使用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

您可以简单地使用csv.reader类将文本文件读取为CSV。您可以将撇号设置为读者的dialect属性的quotechar,将空格设置为delimiter,库将为您处理所有内容。这允许您在其他列上使用撇号来禁用按空格拆分,例如,如果您的电子邮件发件人的fname/lname字段中有一个名字的名字和中间名(请参阅下面示例中的最后一行(。

假设您有以下emails.txt:

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

假设你的.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()

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

  • 第一个索引-名称
  • 第二个索引-消息
  • 第三个索引-状态

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

我会使用regex查找并删除'this is the first message'(这在文件中用引号括起来,对吗?(。

msg = re.findall(r"'.*'", var)
line = re.sub(r"'.*'", "", line)
var = line.split(" ")
var.insert(2, msg)

最新更新