Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用python编写格式良好的文件?_Python_Python 3.x_File_Formatting - Fatal编程技术网

如何用python编写格式良好的文件?

如何用python编写格式良好的文件?,python,python-3.x,file,formatting,Python,Python 3.x,File,Formatting,我正在做一个项目,试图用python编写一个文件,我正在尝试用一个好的格式编写一个文件。我想尝试很多,但我不知道出了什么问题 我会试试: def generate_file(self, lyrics): self.path() print('We are writing file ............') with open('filename.srt', 'w') as lrc: for i in range(

我正在做一个项目,试图用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!')
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()
输出:

    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!')
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()
000:00:00“000-->00:00:00”000由RentAnAdviser.com 100: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生命是一杯饮料,爱情是一杯****900:01:09“812-->00:01:15”0110H n现在我想我一定在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-

我例外:

    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!')
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()
0
00:00:00000-->00:00:00000
由RentAnAdviser.com提供

1
00:00:17842-->00:00:21341
喝我的“喝我的”

2
00:00:21537-->00:00:23336
然后我们将穿越天空拍摄

3
00:00:23546-->00:00:24545
喝我的“喝我的”

我该怎么做?

我的项目:

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

您可以打印(歌词[:10])并查看它是什么样子吗?看起来您正在Windows上读取该文件,但没有将“\r\n”作为EOL。为什么不使用已准备好解析和写入srt文件的库?尝试只使用一个平台,例如linux。当一切都在那里工作时,让它在windows上工作。我使用的是kubuntu linux操作系统。