【问题标题】:Removing line breaks in Python output删除 Python 输出中的换行符
【发布时间】:2021-09-24 11:35:47
【问题描述】:

我正在清理一个文本文件,并编写了以下代码来删除不需要的字符。我的问题是最终输出显示为单词列表,而我希望将其组合为文本。我认为问题出在这一行,它旨在通过替换新行来删除换行符,即用“”

替换“(\n)”
Step4 = re.sub(r"(\n)"," ",Step3)
        print(Step4)

完整代码如下:

f=open("/Applications/Python 3.9/cleaning text.txt",encoding='Latin-1')
raw=f.read()
#print(raw)
import re
import nltk
from nltk import word_tokenize
Data = re.split(r" ",raw)
for D in Data:
#    print(str(raw)+'\n')
    Step1 = re.sub(r"(\\.*)","",D)
#    print(Step1)
    Step2 = re.sub(r"(M)","hl",Step1)
#    print(Step2)
    Step3 = re.sub(r"(\[aa\])","[a::]",Step2)
#    print(Step3)
    Step4 = re.sub(r"(\n)"," ",Step3)
    print(Step4)

【问题讨论】:

  • 你能分享cleaning text.txt文件中的文字吗
  • 在 'Data = re.split(r" ",raw)' 行中,您正在创建一个字符串列表。您应该能够直接在字符串 raw 上替换不需要的符号。

标签: python split nltk


【解决方案1】:

我认为您不需要将整个文本逐字拆分为列表。您可以将原始数据作为 re.sub() 函数的输入。如果您想从原始数据的开头或结尾删除空格字符,您可以使用 strip() 函数。

f=open("/Applications/Python 3.9/cleaning text.txt",encoding='Latin-1')
raw=f.read()
import re

raw = str(raw).strip()
Step1 = re.sub(r"(\\.*)","",raw)
Step2 = re.sub(r"(M)","hl",Step1)
Step3 = re.sub(r"(\[aa\])","[a::]",Step2)
Step4 = re.sub(r"(\n)"," ",Step3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多