繁体   English   中英

如何从 python 列表中的字符串中删除 \n1、\n2、\n3 等?

[英]How to remove \n1, \n2, \n3 etc. from a string in python list?

我创建了一个 python 列表question_text_list ,其中包含从 csv 文件中检索到的字符串(文本)

['text1, 'text2...'text100000']

列表中的文本之一如下所示

'在星际迷航 2013 中,为什么他们\n\n剧透\n剧透\n剧透\n剧透\n\n1让翘曲看起来有点像超空间跳跃\n2这些明亮的粒子在世界上是什么?他们有没有可能让两个实体在曲速空间中分别跳跃做出反应\n4为什么史波克会对这部电影产生情绪\n5把企业藏在水下有什么意义\n6当他们被黑暗的船拦截时,他们为什么会在什么时候到达地球?他们离她很远,似乎不记得他们飞向地球的场景\n7这艘船是如何进入地球大气层的,当时它甚至不在轨道上\n8当斯科蒂打开黑色船的门时,派克和可汗怎么没有减速'

我应用了以下命令,希望我可以删除 \n1, \n2..\n8..and 也 \nspoilers

    question_text_list = [x.replace('\n*',' ').replace('\nspoilers','') for x in question_text_list]

我得到以下 output 这是不可取的,因为我仍然看到 \n1, \n2 删除 \n 但没有像'1','2'这样的尾随数字

'在星际迷航 2013 中,为什么他们 1 让翘曲看起来有点像超空间跳跃 2 世界上那些明亮的粒子一跃起时是什么意思 3 为什么他们让两个实体能够在翘曲空间中在不同的跳跃中做出反应 4 为什么史波克对这部电影产生了情绪5隐藏企业在水下的意义是什么6当他们被黑暗的船拦截时他们是如何在远离她时到达地球的似乎不记得他们扭曲到地球的场景7船是如何进入地球大气层的当它甚至不在轨道8时,当斯科蒂打开黑船的门时,派克和可汗怎么没有减速?

问题- 如何在 Python 中删除所有带有尾随数字的换行符,如 \n1,\n2...?

一个简单的正则表达式就可以解决问题:

import re 

text = 'in star trek 2013 why did they \n\nspoilers ...' # leaving out for brevity
article = re.sub(r'\n[0-9]?(spoilers)?', '', x)

正则表达式\n[0-9]?(spoilers)? 说:

\n => 匹配\n

[0-9]? => 匹配任何数字 0 到 9,但它不必存在( ?部分)

(spoilers)? => 匹配整个单词spoilers ,但它不必存在

您应该为此使用正则表达式:

假设您的变量称为文本,您应该执行以下操作:

import re
text = re.sub(r'\n\d', ' ', text).replace("\nspoilers","").replace("\n","")

这将首先删除所有\nNumbers,因此\n1 \n2 等...第二个替换将简单地删除\nspoilers,第三个将删除任何不需要的\n。 结果将是这样的:

'in star trek 2013 why did they  make warping look quite a bit like an hyperspace jump what in the world were those bright particles as soon as they jumped why in the world did they make it possible for two entities to react in warp space in separate jumps why did spock get emotions for this movie what was the point of hiding the enterprise underwater when they were intercepted by the dark ship how come they reached earth when they were far away from heri dont seem to remember the scene where they warp to earth how did the ship enter earths atmosphere when it wasnt even in orbit when scotty opened the door of the black ship how come pike and khan didnt slow down'

您可以使用:

li = [...] # your orginal list

li = [item.rstrip('\n') for item in li]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM