在 Python 中自动设置文本格式

Automate text formatting in Python

我有一个 txt 文件,其中包含每行的国家/地区代码列表。格式是这样的:

AL
DZ
AS
AO
AI
BS
BB
BY
BJ
BA

我想使用 Python 对文本进行格式化,为每个国家/地区代码添加引号,后跟逗号。

'AL',
'DZ',
'AS',
'AO',
'AI'

你可以这样做

with open('untitled.txt', 'r') as file:
    output =[]
    for l in file:
        output.append("'"+l.strip()+"',\n")

嗯,这是在 python 中完成该任务的一种非正统方法,但是如果您想只使用标准库以最少的行来完成它,那么您可以使用 inputfile 库如下:

$ cat test.txt 
AL
DZ
AS
AO
AI
BS
BB
BY
BJ
BA
$ python3
Python 3.8.10 (default, Jun  2 2021, 10:49:15) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fileinput
>>> for line in fileinput.input("test.txt", inplace=True):
...     print(line.replace(line, f"'{line.strip()}',"))
... 
>>> 

$ cat test.txt 
'AL',
'DZ',
'AS',
'AO',
'AI',
'BS',
'BB',
'BY',
'BJ',
'BA',
$ 

我会这样做:-

with open('flat.txt') as txt:
    cc = []
    for line in txt:
        cc.append("'"+line.rstrip('\n')+"'")
    print(',\n'.join(cc))

另一种还包括写入另一个文件的技术可能如下所示:-

with open('flatin.txt') as txtin:
    with open('flatout.txt', 'w') as txtout:
        txtout.write(',\n'.join(
            "'" + line.rstrip('\n') + "'" for line in txtin) + '\n')