【问题标题】:Split text file Python拆分文本文件 Python
【发布时间】:2018-12-29 12:18:43
【问题描述】:

我正在处理这样的文本文件:

第 1 章

Lorem ipsum

dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt

第02章

consectetur adipiscing

sed 做 eiusmod 时间

第03章

et dolore magna aliqua。

带有“chapter”、“Chapter”、“CHAPTER”等分隔符以及 1 或 2 位数字(“Chapter 1”或“Chapter 01”)。

我设法使用.open().read() 在 Python 中打开和读取文件

mytext = myfile.read()

现在我需要拆分字符串,以获取“第 XX 章”的文本。

对于第 2 章,那就是:

consectetur adipiscing

sed 做 eiusmod 时间

我是 Python 新手,我读过关于 regex、match、map 或 split 的内容,但是……嗯……

(我正在写一个 Gimp Python-fu 插件,所以我使用 Gimp 中捆绑的 Python 版本,即 2.7.15)。

【问题讨论】:

    标签: python string python-2.7 split


    【解决方案1】:

    你可以像这样使用正则表达式:

    import re
    
    split_text = re.split("Chapter [0-9]+\n",  # splits on "Chapter " + numbers + newline
                          mytext, 
                          flags=re.IGNORECASE) # splits on "CHAPTER"/"chapter"/"Chapter" etc
    
    >>> split_text
    ['', '\nLorem ipsum\n\ndolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt\n\n', '\nconsectetur adipiscing\n\nsed do eiusmod tempor\n\n', '\net dolore magna aliqua.']
    

    您现在可以通过split_text 的索引从每个章节中选择文本,例如:

    print(split_text[2])
    
    >>> 
    consectetur adipiscing
    
    sed do eiusmod tempor
    

    【讨论】:

      【解决方案2】:

      你可以试试这个

      chapter = [""]
      for i in range(1,4):
      
        nb1=text.find("Chapter "+ "%02d" % (i,))
        nb2=text.find("Chapter "+ "%02d" % (i+1,))
      
        chapter.append(text[nb1:nb2])
      
      for i in range(1,4):
          print(chapter[i])
      

      或使用正则表达式:

      import re
      
      chapter = re.split("Chapter [0-4]+\n", text)
      
      for i in range(1,4):
          print(chapter[i])
      

      【讨论】:

      • with delimiters like chapter, Chapter, CHAPTER, etc... and 1 or 2 digits (Chapter 1 or Chapter 01) 这没有考虑到“章节”中大小写的可变性,或者超出示例范围的章节编号,或者小于 10 且没有前导 0 的数字(在第一个代码中)块,正则表达式确实捕获了最后一种情况)。
      猜你喜欢
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多