簡體   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