我创建了一个python列表question_text_list,其中包含从csv文件检索的字符串(文本
['text1, 'text2...'text100000']
列表中的一个文本如下所示
在《星际迷航2013》中他们为什么\n\n剧透\n剧透\n剧透\n剧透\n\n1让翘曲看起来很像一次超空间跳跃\n2那些明亮的粒子一跳到底是什么\n3为什么他们让两个实体在翘曲空间分别跳跃时做出反应\n4为什么斯波克对这部电影产生了感情\n5把企业号藏在水下有什么意义\n6当他们被黑暗飞船拦截时他们怎么会在远离它的时候到达地球我似乎不记得他们翘曲到地球的场景\n7当它们被黑暗飞船拦截时飞船是如何进入地球大气层的 它甚至还没有在轨道上\n8当斯科蒂打开黑船的门时,为什么派克和可汗没有减速?
我应用了以下命令,希望我可以删除\n1,\n2...\n8...\n剧透
question_text_list = [x.replace('\n*',' ').replace('\nspoilers','') for x in question_text_list]
我得到了以下输出,这是不理想的,因为我仍然看到\n1,\n2删除\n,但没有看到像'1','2'这样的尾随数字。
在2013年的《星际迷航》中,为什么他们把翘曲变得有点像超空间跳跃?那些明亮的粒子一跳到底是什么?为什么他们让两个实体在翘曲空间分别跳跃时做出反应?为什么斯波克会对这部电影产生感情?把企业号藏在水下有什么意义?当它们被黑暗飞船拦截时,它们怎么会在远离黑暗飞船的时候到达地球?我似乎不记得它们翘曲到地球的场景了?当它们被黑暗飞船拦截时,飞船是如何进入地球大气层的 当斯科蒂打开黑船的门时,它甚至还没有进入轨道,为什么派克和可汗没有减速?
问题-如何删除所有带有尾随数字的换行字符,如\n1,\n2... 用Python?
一个简单的regex就能解决这个问题:
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]?(破坏者)?
表示:
\n
=>; 匹配\n
[0-9]?
=>; 匹配0到9的任意数字,但不一定存在(?
部分)
(剧透)?
=>; 匹配整个单词spoilters
,但不必存在
您应该为此使用正则表达式:
假设您的变量名为text,您应该执行以下操作:
import re
text = re.sub(r'\n\d', ' ', text).replace("\nspoilers","").replace("\n","")
这将首先删除所有\n数字,因此\n1\n2等。。。第二个替换将简单地删除\n扰流板,第三个将删除任何不需要的\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]