Python是一种在Python中每次出现换行符时将文件分割成部分并对这些部分进行操作的方法

2024-05-16 21:32:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个特定格式的纯文本文件,为了简单起见,让我们保持名字、年龄、爱好和空格的顺序,这样继续下去

名称1
年龄1
板球和象棋

名称2
年龄2
板球、网球和曲棍球

等等等等,一直到说名字1000

我正在尝试编写一个python程序,该程序可以将此文件转换为,并将输出保存为新文件
你好,名字1。您的年龄为1岁。你喜欢板球和象棋
你好,名字2。你的年龄是2岁。你喜欢板球、网球和曲棍球
等等

因为我没能做到这一点,所以我试着对2个小样本进行测试,在它们之前添加了这些(姓名:,年龄:,爱好:)

名称:名称1
年龄:1岁
爱好:板球、国际象棋

名称:名称2
年龄:2岁
爱好:板球、网球和曲棍球

我已经编写了下面的代码,但无法正确执行,下面的代码只是又一次不成功的尝试

import re
number = 1
doc = open('profiles.txt', 'r')

def combine(line):
  x = ''
  if re.search("^Name :", line): x = str((line.partition(':'))[2])
  elif re.search("^Age :", line): x = str((line.partition(':'))[2])
  elif re.search("^Hobbies :", line): x = str((line.partition(':'))[2])
  else : pass
  return x
 
for n in doc: 
    # with open('Result.txt', 'a') as file: file.write(str("{0}) Hi {1}. You are aged{1}. You like{1}".format(number,str(combine(n)))))
    print(str("{0}) Hi {1}. You are aged{1}. You like{1}".format(number,str(combine(n)))))
    number += 1

我试着寻找答案,但也许我不知道如何正确地表达。 非常感谢您的帮助


Tags: 程序re名称younumbersearchline曲棍球
3条回答

另一个版本,pedantic和您提供的文件格式,使用.readlines()

readlines()在一次运行中读取所有行,然后将它们作为列表中的字符串元素返回,您可以非常轻松地进行迭代和浏览

with open('text_file.txt', 'r') as file1:
lines = file1.readlines()
 
i = 0
if i <= (len(lines)-3):
    while i in range(len(lines)):
        print (f"Hello, your name is {lines[i][:-1]}, you are {lines[i+1][:-1]} years old and you likes: {lines[i+2][:-1]}")
        i +=4

我的文本文件是:

Mario
45
Cricket and Chess

Tobia
15
Cricket, Tennis and Hockey

Steve Tyler
70
Sex, Drugs, RocknRoll

它打印出:

Hello, your name is Mario, you are 45 years old and you likes: Cricket and Chess
Hello, your name is Tobia, you are 15 years old and you likes: Cricket, Tennis and Hockey
Hello, your name is Steve Tyler, you are 70 years old and you likes: Sex, Drugs, RocknRoll

在第一个实例中,如果您有换行分隔的详细信息,您可以执行以下操作:

file_name = "./details.txt"

def print_details(name, age, hobbies):
    """Helper function to print the details in a nice format"""
    print(f"Hi {name}. You are aged {age}. You like {hobbies}")
    
# add details to a list until a newline is reached, print then reset
with open(file_name, 'r') as fin:
    details = []
    for line in fin:
        if line == '\n':
            print_details(*details)
            details = []
        else:
            details.append(line.strip())
    print_details(*details)

我认为这是一种更简单的方法(基于您建议的第二种文件格式):-

DEFAULT = {'Name': '', 'Age': '', 'Hobbies': ''}
with open('/Users/andy/profiles.txt') as p:
    d = dict(DEFAULT)
    for line in p:
        line = line.rstrip('\n').strip()
        if len(line) == 0:
            print(
                f'Hi {d["Name"]}. Your age is {d["Age"]}. You like {d["Hobbies"]}')
            d = dict(DEFAULT)
        else:
            t = line.split(':')
            if len(t) == 2:
                d[t[0].strip()] = t[1].strip()

相关问题 更多 >