好的,所以我正在尝试格式化一个大的文本文档以进行转换。
#{'000','001','002','003','004','005','006','007','008','009'}转到
#{'000':'001','002':'003','004':'005','006':'007','008':'009'}使用python并让我的函数工作,但是只有在我逐行运行它时,它才能工作。
并且想知道如何让它在我输入的每一行中运行,这样它就可以在多行文档上工作。
with open("input") as core:
a = core.read()
K = '!'
N = 12
res = ''
for idx, ele in enumerate(a):
if idx % N == 0 and idx != 0:
res = res + K
else:
res = res + ele
b = (str(res).replace(",",":").replace("!",","))
l = len(b)
c = b[:l-1]
d = c + "}"
print(d)以下是多行文本文件的当前结果
{'000':'001','002':'003','004':'005','006':'007','008':'009',
{'001':'00,':'003':'00,':'005':'00,':'007':'00,':'009':'00,'}
{'002':',03':'004':',05':'006':',07':'008':',09':'000':',01'}
{'003','004':'005','006':'007','008':'009','000':'001','002'}到目前为止我已经试过了
with open('input', "r") as a:
for line in a:
K = '!'
N = 12
res = ''
for idx, ele in enumerate(a):
if idx % N == 0 and idx != 0:
res = res + K
else:
res = res + ele
b = (str(res))
l = len(b)
c = b[:l-1]
d = c + "}"
print(d)但没有运气
找到了一个解决方案
import re
with open("input") as core:
coords = core.read()
sword = coords.replace("\n",",\n")
dung = re.sub('(,[^,]*),', r'\1 ', sword).replace(",",":").replace(" ",",").replace(",\n","\n")
print(dung)我知道我的解决方案是有效的,但我不能完全将它应用于其他情况,在这些情况下,我将根据需要应用不同的格式。很容易解决如何格式化一行文本,因为有这么多的文档。
有没有人知道任何插件或特定的python元素,您可以在其中编写格式函数,然后将其应用于所有行。类似于一种applyline()扩展,而不是readline()
发布于 2022-02-28 18:10:19
对于给定的示例输入,您可以使用.read()一次读取整个文件,使用模式匹配第一个逗号,并在第1组中捕获匹配直到第二个逗号。
在替换中,使用:并使用\1反向引用第1组中捕获的内容
,([^,\n]*,)?部分匹配的模式:
,匹配逗号( Capture group 1 [^,\n]*,可以选择匹配除逗号或换行符以外的任何字符,然后匹配逗号。)?关闭捕获组并使其成为可选的例如:
import re
with open("input") as core:
dung = re.sub(r",([^,\n]*,)?", r":\1", core.read())
print(dung)输出
#{'000':'001','002':'003','004':'005','006':'007','008':'009'}https://stackoverflow.com/questions/71297371
复制相似问题