用特定格式写入文件

时间:2017-04-17 17:12:57

标签: python class text format

function Recycle-Item($Path) { $item = Get-Item $Path $directoryPath = Split-Path $item -Parent $shell = new-object -comobject "Shell.Application" $shellFolder = $shell.Namespace($directoryPath) $shellItem = $shellFolder.ParseName($item.Name) $shellItem.InvokeVerb("delete") } 是一个方法,当文件保存时它只会以这种格式写入:

def sauvegarder_canaux(self, nom_fichier:str)

我需要它像这样:

5 - TQS (Télévision Quatres-saisons, 0.0 $ extra) 

这是我现在的代码:

5 : TQS : Télévision Quatres-saisons : 0.0 $ extra

2 个答案:

答案 0 :(得分:0)

您只需在编写字符串之前编辑该字符串。字符串。替换命令是你的朋友。也许......

    for i in self.__canaux:
        out_line = str(i)
        for char in "-(,":
            out_line = out_line.replace(char, ':')
        fichCanaux.write(out_line + "\n")

答案 1 :(得分:0)

如果删除重音是可以的,您可以使用NFD将文本规范化为unicodedata,然后找到感兴趣的片段,使用所需的格式修改它们,并使用格式化的片段替换它们regex

import unicodedata
import re

def format_string(test_str):
    # normalize accents
    test_str = test_str.decode("UTF-8")
    test_str = unicodedata.normalize('NFD', test_str).encode('ascii', 'ignore')

    # segment patterns
    segment_1_ptn = re.compile(r"""[0-9]*(\s)*                    # natural number
                                   [-](\s)*                       # dash
                                   (\w)*(\s)*                     # acronym
                                """,
                               re.VERBOSE)
    segment_2_ptn = re.compile(r"""(\w)*(\s)*                     # acronym
                                   (\()                           # open parenthesis
                                   ((\w*[-]*)*(\s)*)*             # words
                                """,
                               re.VERBOSE)
    segment_3_ptn = re.compile(r"""((\w*[-]*)*(\s)*)*             # words
                                   (,)(\s)*                       # comma
                                   [0-9]*(.)[0-9]*(\s)*(\$)(\s)   # real number
                                """,
                               re.VERBOSE)

    # format data
    segment_1_match = re.search(segment_1, test_str).group()
    test_str = test_str.replace(segment_1_match, " : ".join(segment_1_match.split("-")))
    segment_2_match = re.search(segment_2, test_str).group()
    test_str = test_str.replace(segment_2_match, " : ".join(segment_2_match.split("(")))
    segment_3_match = re.search(segment_3, test_str).group()
    test_str = test_str.replace(segment_3_match, " :     ".join(segment_3_match.split(",")))[:-1]
    test_str = " : ".join([txt.strip() for txt in test_str.split(":")])

    return test_str

然后你可以在sauvegarder_canaux

中调用此函数
def sauvegarder_canaux(self, nom_fichier:str):
    with open(nom_fichier, "w") as fichCanaux
        for i in self.__canaux:
            fichCanaux.write(format_string(str(i)) + "\n")

您还可以在format_string课程中添加Distributeur作为方法。

示例输入:     5 - TQS (Télévision Quatres-saisons, 0.0 $ extra)

示例输出:     5 : TQS : Television Quatres-saisons : 0.0 $ extra