【问题标题】:Automate text formatting in Python在 Python 中自动格式化文本
【发布时间】:2021-07-27 09:32:43
【问题描述】:

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

AL
DZ
AS
AO
AI
BS
BB
BY
BJ
BA

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

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

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 没什么:(

标签: python text formatting txt


【解决方案1】:

我会这样做:-

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')

【讨论】:

  • 我忘了说输出应该是另一个txt文件
  • 你想让我也写那部分吗?
  • 那将是理想的,是的 ??
  • 非常正确@Timus。我最初在 join() 之外声明了列表理解(到一个临时变量中),然后复制并粘贴而不考虑它。感谢您强调我的错误。我将编辑代码
【解决方案2】:

嗯,这是在 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',
$ 

【讨论】:

  • 不幸的是,这会导致多余的尾随逗号
【解决方案3】:

你可以这样做

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

【讨论】:

  • 与其他解决方案之一一样,这将在末尾生成一个多余的逗号
  • 据我了解,作者希望在每一行的末尾都有一个昏迷
  • 不是根据他在问题中显示的示例输出
  • 对不起你是对的我调整了答案谢谢
  • 现在不会有逗号了!
猜你喜欢
  • 2015-11-06
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 2013-04-13
  • 1970-01-01
相关资源
最近更新 更多