Python中如何去除换行符

Python中如何去除换行符

首先要了解’\\n’和’\n’的区别:

print("a\\nb")
print("a\nb")

输出效果:

a\nb
a
b

方法1. exlude函数
exclude即排出的意思,include的反义词。
但在文本文件中使用exclude函数去除换行符时,其实无关紧要,\\n,\n皆可除。

fi = open("arrogant.txt","r")
fo = open("PY301-1.txt","w")
txt = fi.read()
d = {}
exclude = "! ? , . : ; \" \n -"
# 写成\\n也可以
for line in txt:
    if line in exclude:
        continue
    else:
        d[line]=d.get(line,0)+1
ls =list(d.items())
print(ls)

因为在文本文件中实际上都是当作字符串’\n’去除的,这是第一种方法。

方法2. del d[’\n’]

fi = open("arrogant.txt","r")
fo = open("PY301-1.txt","w")
txt = fi.read()
d = {}
exclude = "! ? , . : ; \" -"
for line in txt:
    if line in exclude:
        continue
    else:
        d[line]=d.get(line,0)+1
del d['\n']

当用字典来受集文本数据的时候,直接删除键即可。

方法3. replace(’\n’, ‘’)

fi = open("arrogant.txt","r")
fo = open("PY301-1.txt","w")
txt = fi.read()
d = {}
exclude = "! ? , . : ; \" -"
for line in txt:
    line = line.replace("\n", "")
    # 直接替换成空
    if line in exclude:
        continue
    else:
        d[line]=d.get(line,0)+1

方法4:strip函数

fi = open("arrogant.txt","r")
fo = open("PY301-1.txt","w")
txt = fi.read()
d = {}
exclude = "! ? , . : ; \" -"
for line in txt:
    line = line.strip()
    if line in exclude:
        continue
    else:
        d[line]=d.get(line,0)+1

用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
CSV中常用于删除数据换行符。

发布了6 篇原创文章 · 获赞 4 · 访问量 1258

猜你喜欢

转载自blog.csdn.net/wayne6515/article/details/104261173