[英]How do I convert a list in a .txt file to a list in Processing (python)?
我的家庭作業遇到了問題。 在文本文件中,有以下內容:
ignored = ["the", "a", "an", "i", "me", "you", "with", "this"]
(實際內容要長得多,但為了簡單起見,我縮短了它。)
我希望 .txt 文件中顯示的列表成為我的處理應用程序中的列表。
我嘗試使用 .strip 和 .split 使其工作:
size(500,500)
ignored = []
g = open("ignored.txt", "r")
for line in g:
line = line.strip('ignored')
line= line.strip()
line = line.strip("=")
line = line.strip()
line = line.strip("][")
line = line.split(", ")
print(line)
ignored.append(line)
ignored.pop()
print(ignored)
我嘗試了 .strip 或 .split 的多種組合,但我的打印輸出一直是這個或類似的東西。
[['"the"', '"a"', '"an"', '"i"', '"me"', '"you"', '"with"', '"this"']]
我希望我的最終列表缺少額外的引號和括號。 類似於:["the", "a", "an", "i", "me", "you", "with", "this"]
我無法找到一種方法來完成這項工作,我認為有一種更簡單的方法。
我無法導入任何內容,並且我使用的是最新版本的 Processing。 對於上下文(如有必要):我的最終目標是從“忽略”列表中取出單詞並從另一個列表中刪除這些單詞。
如果有的話,請告訴我您需要什么其他信息來幫助我。 謝謝你的時間。
您可以使用正則表達式( import re
):
my_list = re.findall(r'"(\w+)"', line)
ignored.append(my_list)
這樣,您將獲得for
循環中每一行的列表。 或者,你可以這樣:
ignored = re.findall(r'"(\w+)"', g.read())
使用這個簡單的行,您可以獲得文件中""
之間的所有內容的列表。
由於您正在加載的文件中包含實際的 Python 代碼,因此獲取它的一種方法是復制或重命名它並導入它。 顯然不是一般推薦的東西,如果事實上它有點麻煩,但任務似乎假設你在這種情況下會做類似的事情。
import shutil
shutil.copy('ignored.txt', 'ignored.py')
from ignored import ignored
print(ignored)
除了不安全之外,這還有一個缺點,就是告訴您它無法從檢查這些內容的編輯器中找到被忽略的模塊,就像大多數 IDE 一樣。 另一個簡單但也不是很安全的解決方案是將文件的內容作為 Python 進行評估而不導入它。
ignored = []
with open('ignored.txt', 'r') as f:
content = f.read()
exec(content)
print(ignored)
一個更安全且可以說是更好的解決方案是解析文件的內容並只選擇您想要的元素。 但是,不是像您的示例那樣手動執行此操作,而是可以使用正則表達式來獲取您需要的內容 - 假設它只包含與您提供的類似的行:
import re
with open('ignored.txt', 'r') as f:
content = f.read()
ignored = [match.group(1) for match in re.finditer('[\'"](.*?)[\'"]', content)]
print(ignored)
請嘗試以下操作:
ignored = []
g = open("text.txt", "r")
for line in g:
start_index = line.find('[') + 1
end_index = line.find(']')
l = line[start_index:end_index]
l = l.replace('"', '')
l = l.split()
ignored.extend(l)
print(ignored)
使用此代碼應該相當簡單:
import ast
with open("ignored.txt", "r") as f:
f = f.read().strip("ignored = ")
print(ast.literal_eval(f))
Out[0]: ['the', 'a', 'an', 'i', 'me', 'you', 'with', 'this']
請注意, with open()
一起使用通常更好、更簡潔,因為它會在您完成使用相關文件后自動關閉您的文件以釋放任何浪費的內存。 否則,請確保在完成對文件的讀取或寫入后運行f.close()
。
看起來您只需要再次使用 strip 即可從文本文件中刪除引號。
此外,在使用 split(",") 之前使用 find() 從輸入中定位 [] 可能更少編碼。
您最好將正則表達式用於像這樣的文本解析任務。 它是解析文本的最佳工具。 在txt文件中提取列表的示例代碼如下:
import re
with open('test.txt', 'rb') as f:
line = f.readline()
pattern = '"(.*?)"' # this means: any characters between double quotation marks
ignored = re.findall(pattern , line) # this method returns a list of strings that match pattern
上面代碼中的一些假設:
您的 txt 文件名為 test.txt,它只有 1 行,該行包含列表。
您的列表是一個字符串列表,每個字符串都包含在一對雙引號內。
re
是 Python 中的內置模塊,因此無需安裝任何第三方庫。 可以在此處找到有關正則表達式的更多信息。
我能夠通過以下方式做到這一點:
text1='''ignored = ["the", "a", "an", "i", "me", "you", "with", "this"]'''
list1=text1.split('[')[-1][:-1].replace('"','').split(',')
print(list1)
Out: ['the', ' a', ' an', ' i', ' me', ' you', ' with', ' this']
或者用這個
list1=text1.split('[')[-1].strip(']').replace('"','').split(',')
我只是硬編碼了您的文本行,以便於測試。
忽略 = ["the", "a", "an", "i", "me", "you", "with", "this"]
with open("ignored.txt", "r") as f:
for line in f:
if line.startswith('ignored = ['):
list = line.replace('ignored = [','').replace(']').replace('"', '').strip(',')
print list
使用替換:
line.replace('"','').replace('[','') etc...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.