gpt4 book ai didi

Python排列列表并将其写回文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:50 24 4
gpt4 key购买 nike

我正在尝试制作一个脚本来查找文本文档中符号 {} 之间的所有内容。它采用 {} 中的 .txt 文档特定部分并按字母顺序对其进行组织,然后将其写回文本文档。文本文档示例..

bla bla bla 
bla ba bl bla ba bl {apple:banana, this: something else, airplane:hobby}
bla bla bla
bla bla bla

期望的输出(按字母顺序排序)..

bla bla bla 
bla ba bl bla ba bl {airplane:hobby, apple:banana, this: something else}
bla bla bla
bla bla bla

还在打印什么..

    bla bla bla 
bla ba bl bla ba bl {apple:banana, this: something else, airplane:hobby}
bla bla bla
bla bla bla

我的代码..

def openFind():
f = open(inFile, 'r')
lines = f.read()
match = re.findall(r'{(.*?)}', lines)
before = str(match)
n=1
for i in xrange(0, len(match), n):
mydict = match[i:i+n]
for x in sorted(mydict):
c = x.split(',')
newmatch = sorted(c)
final = str(newmatch)
print final

# NOT WORKING BELOW!!! Stuck in loop?
with open(outFile,'w') as new_file:
with open(inFile) as old_file:
for line in old_file:
new_file.write(line.replace(before, after))

它将排序/按字母顺序排列的列表打印为 [airplane:hobby, apple:banana, this: something else],但如何用它来替换文本文档中的原始文本?必须到位,但可以创建新的 txt。

最佳答案

这应该有效:

import re

def openFind():
with open("test.txt", "r") as in_file:
data = in_file.read()

def sub(m):
l = [s.strip() for s in m.group(1).split(",")]
l.sort()
return "{%s}" % (", ".join(l),)

replacement = re.sub(r'{(.*?)}', sub, data)
with open("out.txt", "w") as out_file:
out_file.write(replacement)

我用过re.sub()以便替换为已排序的就地匹配项。

关于Python排列列表并将其写回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36553318/

24 4 0