簡體   English   中英

將文本文件存儲在列表中,然后去除列表中的空格、逗號和撇號

[英]Storing a text-file in a list, then stripping white spaces, commas and apostrophes in the list

我正在嘗試刪除列表中的所有空格、逗號和撇號,它們來自用戶將輸入的文本文件。 我正在嘗試將其過濾為僅顯示數字(中間沒有空格)。

我試圖刪除變量“file_strip”中的空格、逗號、方括號和撇號,但它的輸出似乎與“file_stored_in_list”相同。

有人幫我想出一個解決方案來將文本文件過濾為數字嗎? 如果有更有效的閱讀文本文件的方法,請告訴我! 謝謝!

filename = input("Input the name of the file: ")
file = open(filename, "r")

#Stores the text file into a list
file_stored_in_list = file.read().splitlines()    
file.close()

#from .txt file: Outputs ['2        7        6', '9        5        1', '4        3        8']
print(file_stored_in_list)


#Attempted to remove white-spaces, tried with commas, sqaure 
brackets and apostrophes, left blank for now
file_strip = [i.strip(" ") for i in file_stored_in_list]

#Outputs the same ['2        7        6', '9        5        1', '4        3        8']
print(file_strip)

糟糕...您正在嘗試刪除文件中不存在的字符!

我敢打賭,文件的內容只是:

2        7        6
9        5        1
4        3        8

但是你讀它:

file = open(filename, "r")

#Stores the text file into a list
file_stored_in_list = file.read().splitlines()    
file.close()

從那時起, file_stored_in_list是一個不錯的字符串列表。 為了確保它,只需逐行打印:

for line in file_stored_in_list:
    print(line)

但是當您打印列表時,python 會在列表周圍打印方括號 ( [] ),並打印元素的表示 字符串的表示是用引號括起來的字符串......

順便說一句,逐行讀取文件的正確方法是:

with open(filename) as file:
    for line in file:
        # process the line...

解決這個問題的一種方法是翻譯:

translation = str.maketrans("", "", " \t,[]'")
file_strip = [item.translate(translation) for item in file_stored_in_list]

另一種方法是使用正則表達式:

import re
reg = re.compile(r'\D') # \D is anything other than digits
file_strip = [re.sub(reg, '', item) for item in file_stored_in_list]

值得注意的是, strip(" ")不能按您預期的方式工作 - 它只會從字符串的開頭和結尾刪除空格。 請參閱文檔

正則表達式子應該可以解決問題。

import re
mylines = []
with open(myfile) as f: #better, more pythonic
    mylines = f.readlines()

clean_lines = []
clean_lines = [re.sub(r"\s+", " ", l) for l in mylines]

當我嘗試時,這對我有用:

>>> import re
>>> re.sub(r"\s+", " ", "a      b      c")
'a b c'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM