首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >写入特定格式的文件

写入特定格式的文件
EN

Stack Overflow用户
提问于 2017-04-18 01:12:57
回答 2查看 34关注 0票数 0

当文件仅以这种格式保存时,def sauvegarder_canaux(self, nom_fichier:str)方法会给我带来问题:

代码语言:javascript
复制
5 - TQS (Télévision Quatres-saisons, 0.0 $ extra) 

我需要这样做:

代码语言:javascript
复制
5 : TQS : Télévision Quatres-saisons : 0.0 $ extra

这是我现在拥有的代码:

代码语言:javascript
复制
from canal import Canal
from forfait_tv import ForfaitTV
from abonne import Abonne


#============= Classe ===========================
class Distributeur :
    """
    Description :
    ===========
    Cette classe gère les listes de canaux, de forfaits (et plus tard
    d'abonné).


    Données membres privées :
    ======================
    __canaux        # [Canal]     Liste de canaux existants
    __forfaits      # [ForfaitTV] Liste des forfaits disponibles
    """


    #-----------  Constructeur -----------------------------
    def __init__(self):
        self.__canaux = None
        self.__forfaits = None
        #code
        self.__canaux = [] #list
        self.__forfaits = [] #list





    #----------- Accesseurs/Mutateurs ----------------------
    def ajouter_canal(self,un_canal:Canal):
        self.__canaux.append(un_canal)


    def chercher_canal (self,p_poste:int):
        i=0
        postex = None
        poste_trouve=None
        for i in range(0,len(self.__canaux),1):
            postex=self.__canaux[i]
            if postex.get_poste()== p_poste:
                poste_trouve=postex
                return print(poste_trouve)



    def telecharger_canaux(self,nom_fichier:str):

        fichierCanaux = open(nom_fichier, "r")
        for line in fichierCanaux:
            eleCanal = line.strip(" : ")
            canal = Canal(eleCanal[0],eleCanal[1],eleCanal[2],eleCanal[3])
            self.__canaux.append(canal)
            return canal


    def sauvegarder_canaux(self, nom_fichier:str):
        fichCanaux = open(nom_fichier,"w")
        for i in self.__canaux:
            fichCanaux.write(str(i) + "\n")

        fichCanaux.close()
EN

回答 2

Stack Overflow用户

发布于 2017-04-18 01:21:33

您只需在编写字符串之前对其进行编辑。string.replace命令是您的朋友。也许..。

代码语言:javascript
复制
    for i in self.__canaux:
        out_line = str(i)
        for char in "-(,":
            out_line = out_line.replace(char, ':')
        fichCanaux.write(out_line + "\n")
票数 0
EN

Stack Overflow用户

发布于 2017-04-18 02:46:04

如果可以移除重音符号,则可以使用unicodedata将文本规范化为NFD,然后找到感兴趣的片段,使用所需的格式对其进行修改,并使用regex将其替换为格式化的片段

代码语言:javascript
复制
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中调用此函数

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43456067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档