【问题标题】:Google Colab Paragraph RemovalGoogle Colab 段落删除
【发布时间】:2020-08-25 14:35:08
【问题描述】:

我需要帮助从 Google Colab 上的此文本文件 (https://www.gutenberg.org/files/768/768.txt) 中删除段落。我需要文本文件在“ccx074@pglaf.org”之后开始,并在“END OF THE PROJECT GUTENBERG EBOOK WUTHERING HEIGHTS”之前结束,以便获得准确的总字数。下面列出的是我到目前为止的编码。

# download and installing pyspark in colab
!pip install -q pyspark

# download Wuthering Heights, by Emily Bronte
!wget -q https://www.gutenberg.org/files/768/768.txt

import os.path
baseDir = os.path.join('data')
inputPath = os.path.join('/content/768.txt')
fileName = os.path.join(baseDir, inputPath)
with open('/content/768.txt','r') as f:
print(f.read())

【问题讨论】:

    标签: python google-colaboratory


    【解决方案1】:

    只需在找到要查找的文本的点处对字符串进行切片。

    !wget -q https://www.gutenberg.org/files/768/768.txt
    import os.path
    baseDir = os.path.join('data')
    inputPath = os.path.join('768.txt')
    fileName = os.path.join(baseDir, inputPath)
    with open('768.txt','r') as f:
        text = f.read()
        
    #GET START LOC
    start_loc = text.find("ccx074@pglaf.org") + len("ccx074@pglaf.org")
    #GET END LOC
    end_loc = text[start_loc:].find("***")
    #SLICE THE TEXT STRING AND THE INDEXES 
    text[start_loc:start_loc+end_loc].replace("\n","")
    

    【讨论】:

    • 您能帮我删除文档中多余的空格('/n)吗?
    • 如果对您有帮助,请接受。我已经编辑了答案
    • 谢谢。我试图给它投票,但它没有让我。
    • 点击勾号:)
    【解决方案2】:

    您可以使用正则表达式来提取两个字符串之间的文本:

    import re
    text = open('768.txt','r').read()
    
    start = "ccx074@pglaf.org"
    end = "END OF THE PROJECT GUTENBERG EBOOK WUTHERING HEIGHTS"
    
    m = re.search(f'{start}(?s)(.*){end}', text)
    print(m.group(1))
    

    【讨论】:

    • 当我使用该编码时,我收到一个错误,指出预期的字符串或字节之类的对象。
    猜你喜欢
    • 2015-12-16
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多