首页 > 解决方案 > 如何用python以良好的格式编写文件?

问题描述

我在一个项目中,试图用 python 编写文件,我正在尝试以很好的格式编写文件。我会尝试很多,但我不知道出了什么问题?

我会尝试:

    def generate_file(self, lyrics):
        self.path()
        print('We are writing file ............')
        with open('filename.srt', 'w') as lrc:
            for i in range(len(lyrics)):
                add = ''
                if lyrics[i].isnumeric():
                    add += '\n'
                elif lyrics[i].isalpha():
                    add += '\n\n'
                lrc.write(lyrics[i]+add)
                add += ''
            lrc.close()
            print('We downloaded your file!')

输出:

000:00:00‚000 --> 00:00:00‚000by RentAnAdviser.com100:00:22‚608 --> 00:00:26‚607从我这里喝 噢噢噢噢200:00:26‚803 --> 00:00:30‚602然后我们将穿越交响曲300:00:30‚808 --> 00:00:38‚807然后我们将穿越天空400:00:43‚599 --> 00 :00:48‚498哦天使从天而降500:00:48‚702 --> 00:00:53‚801你知道你让我的世界亮起来600:00:54‚005 --> 00:00:59‚004什么时候当我受伤的时候我很沮丧700:00:59‚218 --> 00:01:04‚717你来扶我起来800:01:04‚911 --> 00:01:09‚610生活是一种饮料和爱' s a ****900:01:09‚812 --> 00:01:15‚011哦,现在我想我一定要跑几英里了1000:01:15‚217 --> 00:01:20‚316当我受伤时枯萎干涸1100:01:20‚506 --> 00:01:26‚005你来了一场洪水1200:01:26‚217 --> 00:01:28‚716所以从我这里喝水从我这里喝1300:01:28‚ 900 -

我例外:

0
00:00:00,000 --> 00:00:
00,000 by RentAnAdviser.com

1
00:00:17,842 --> 00:00:21,341
从我这里喝,从我这里喝

2
00:00:21,537 --> 00:00:23,336
然后我们将穿越天空

3
00:00:23,546 --> 00:00:24,545
从我这里喝,从我这里喝

我怎样才能做到这一点?

我的项目:

from bs4 import BeautifulSoup
import os, requests, platform


class EpicLyricFinderApp:
    def __init__(self):
        self.text = '%20'.join(input('Enter song name and also include singer: ').split(' '))
        self.url = 'https://www.rentanadviser.com/en/subtitles/subtitles4songs.aspx?src='+self.text
        self.user = None


        self.app()
    def app(self):
        req = requests.get(self.url).content
        soup = BeautifulSoup(req, 'html.parser')
        print('Please wait ...................')
        tag = soup.findAll('table')
        link = [('https://www.rentanadviser.com/en/subtitles/'+l.get('href'))+'&type=srt' for l in [a.find('a') for a in tag]]
        blank_name = [''.join((l.get_text()).split(' ')[17:]) for l in [a.find('a') for a in tag]]
        [print('No. {} ==>> {}'.format(name+1,blank_name[name])) for name in range(len(blank_name))]


        # Get input form user to choice lyrics
        print('='*60)
        while True:
            try:
                 self.user = int(input('Which lyrics you wanna download?: '))
            except ValueError:
                continue
            else:
                break


        # Open .srt link
        req1 = requests.get(link[self.user]).content
        soup1 = BeautifulSoup(req1, 'html.parser')
        lyrics = [c.get_text() for c in soup1.findAll('span', attrs={'id':'ctl00_ContentPlaceHolder1_lblSubtitle'})]
        self.generate_file(lyrics)





    @staticmethod
    def path():
        if platform.system()=='Linux':
            linux = '/home/rohit/Desktop/lrc'
            if os.path.exists(linux):
                os.chdir(linux)
            else:
                os.mkdir(linux)
                os.chdir(linux)
        else:
            windows = 'Cd:/Users/ABC/rohit/Desktop/lrc'
            if os.path.exists(windows):
                os.chdir(windows)
            else:
                os.mkdir(windows)
                os.chdir(windows)

    def generate_file(self, lyrics):
        self.path()
        print('We are writing file ............')
        with open('_'.join(self.text.split('%20'))+'.srt', 'w') as lrc:
            for i in range(len(lyrics)):
                add = ''
                if lyrics[i].isnumeric():
                    add += '\n'
                elif lyrics[i].isalpha():
                    add += '\n\n'
                lrc.write(lyrics[i]+add)
                add += ''
            lrc.close()
            print('We downloaded your file!')



if __name__ == '__main__':
    app = EpicLyricFinderApp()

标签: pythonpython-3.xfileformatting

解决方案


推荐阅读