对文本文件进行排序和重新格式化



需要以下方面的帮助:

  1. 从一个字符串读取到另一个指定字符串
  2. 将两个单独行上的字符串合并到一行上,我尝试了strip((,但没有成功
  3. 根据提供的文本创建2个单独的数组

给定:

Cat Chores
Get 
cat food.
Dog Chores
Get
dog food. Walk Dog.

期望输出:

Cat Chores
Get cat food.

这些句子是分开的,因为它们将被放在一个数组中。

Dog Chores
Get dog food. Walk Dog.

最终输出:

cat_chores = [Get cat food.]
dog_chores = [Get dog food. , Walk Dog]

这是我的代码:

# Remove whitespace and reformat the file
with open('chores.txt',"r") as f:
text = input.read()
text = [lines.strip() for lines in text] 
with open('chores.txt',"w") as f:
f.writelines(text)
f.close
# Re-open the file to create the arrays.
with open('chores.txt',"r") as f:
text = input.read()
if "Cat Chores" in text:
print (line,end='')
print(next(input),end='')
if "Dog Chores" in text:
print (line,end='')
print(next(input),end='')

试试这个:

chores = {}
action = ''
with open('chores.txt', 'r') as f:
for line in f.read().splitlines():
line = line.strip()  # your original data had trailing spaces. this is to remove them
if 'Chores' in line:  # check if line is a grouping
current_chore = line
chores[current_chore] = []
elif len(line.split(' ')) == 1:  # check if line is an action
action = line + ' '
continue
else:
chores[current_chore].append(action + line)
action = ''
with open('chores.txt', 'w') as f:
f.write(str(chores))
f.close

它将输出:

{'Cat Chores': ['Get cat food.'], 'Dog Chores': ['Get dog food. Walk Dog.']}

这假设一个分组总是包含"Chores",动作总是一个单词,并输出一个字典字符串。我的版本没有把"吃狗粮"分开和"遛狗"但如果你想,你可以在"上添加一个split((并处理它。你输入数据的格式很糟糕,真的不应该按原样使用。

最新更新