![](/img/trans.png)
[英]How do I use zip print on a list of strings in python without it returning with quotations surrounding them?
[英]How can I remove double quotations surrounding a list imported from a file in Python?
我正在嘗試創建一個食品存儲應用程序,用於跟蹤放入食品存儲設施的物品並為用戶召回它們。 這是該程序的早期原型,只能在本地跟蹤信息,但我遇到了一些問題。 因此,如果這段代碼不可讀,我深表歉意,我就是找不到下面解釋的問題的解決方案。
print("Food Storage Application V1.0 - LOCAL ONLY")
UPC_List = []
with open('UPCList.txt', 'r') as file:
for UPCentry in file:
location = UPCentry[:-1]
UPC_List.append(location)
print(UPC_List)
global i
i = 0
UPC_Input = ''
UPC_Count = 0
while True:
UPC_Found = False
UPC_Input = input("Enter UPC or enter 'end' to quit: ")
if UPC_Input == "end":
with open("UPCList.txt", "w") as file:
for UPCsave in UPC_List:
file.write('%s\n' % UPCsave)
break
try:
UPC_Input = int(UPC_Input)
except ValueError as v:
print(f"Input '{UPC_Input}' is not an acceptable UPC")
continue
# print(UPC_List) # for debugging
def newProduct(UPC):
global UPC_Count
product_name = input(f"Enter name of item {UPC}: ")
product_quantity = input(f"Enter quantity of item {UPC}: ")
try:
product_quantity = int(product_quantity)
except ValueError as v:
print("Invalid quantity. Please enter a number.")
newProduct(UPC_Input)
product_unit = input(f"Enter unit type (box, bunch, can, etc...) of item {UPC}: ")
print(f"You have added: \n {product_name} \n {UPC} \n Quantity: {product_quantity} \n Unit: {product_unit}")
UPC_List.insert(UPC_Count, [UPC, product_name, product_quantity, product_unit])
UPC_Count += 1
def existingProduct(UPC):
for sublist in UPC_List:
if str(UPC) in str(sublist):
UPC = int(UPC)
print(f"Position: {UPC_List.index(sublist)} {sublist.index(UPC)}")
position = UPC_List.index(sublist)
addition = input(f"Enter the number of items to add to '{UPC_List[position][1]}' (Default entry: +1): ")
try:
addition = int(addition)
except ValueError as v:
addition = 0
if addition == 0:
UPC_List[position][2] += 1
else:
UPC_List[position][2] += addition
print(f"New Quantity for item '{UPC_List[position][1]}': {UPC_List[position][2]}")
#Find if UPC Exists
for UPC in UPC_List:
if UPC[0] == UPC_Input:
print("UPC Found")
existingProduct(UPC_Input)
UPC_Found = True
if UPC_Found == False:
newProduct(UPC_Input)
到目前為止,這是我的代碼。 我制作了一個沒有讀取和寫入文件行的版本並且它工作得很好,但我很難讓代碼從文件中讀取列表並在代碼中使用它。 它保存列表,但不會正確檢索它。 我通過使用print(UPC_List)
行發現了我認為的問題,該行打印["[2, 'banana', 2, 'bunch']"]
(這是我使用程序加載到文件中的測試條目). 我認為問題出在列表外面的雙引號上。 這是一個嵌套列表,因此當我嘗試訪問該列表時,那些引號會導致索引錯誤。
如果這還不夠,我可以嘗試提供更多信息。 我是 python 的新手並且一般都在編碼,所以這是我對腳本的最佳嘗試。
您正在以字符串形式讀取每個列表。
您可以使用 python eval
function 將字符串轉換為其評估形式:
my_list_string = "['item1', 'item2']"
my_list = eval(my_list_string)
要重現和解決,我們需要一個最小的可重現示例,包括
UPCList.txt
的內容:
[2, 'banana', 2, 'bunch']
這是 Python 中列表的字符串表示形式(如str(list)
)。 可能是你的程序寫的。
一個最小的可重現示例(僅前幾行打印閱讀列表):
upc_locations = []
with open('UPCList.txt', 'r') as file:
for upc in file:
location = upc[:-1]
upc_locations.append(location)
print(upc_locations)
印刷:
["[2, 'banana', 2, 'bunch']"]
為讀取的每一行添加一些調試打印
upc_locations = []
with open('UPCList.txt', 'r') as file:
for line in file:
print(line)
location = line[:-1] # read all chars from line until last (excluding)
print(location)
upc_locations.append(location)
print(upc_locations)
印刷:
[2, 'banana', 2, 'bunch']
[2, 'banana', 2, 'bunch']
["[2, 'banana', 2, 'bunch']"]
筆記:
\n
。該行可以解析為 JSON 數組。 因此,我們需要先用雙引號替換單引號。
import json
upc_locations = []
with open('UPCList.txt', 'r') as file:
for line in file:
cleaned = line.strip() # remove the line-break and any surrounding whitespace
print(cleaned)
valid_json = cleaned.replace("'", '"') # replace single quotes by double quotes to have valid JSON strings
array = json.loads(valid_json)
print(array)
for element in array:
upc_locations.append(element)
print(upc_locations)
印刷:
[2, 'banana', 2, 'bunch']
[2, u'banana', 2, u'bunch']
[2, u'banana', 2, u'bunch']
將程序中的對象保存到純文本文件時,建議使用標准格式,如 CSV、XML 或 JSON。這樣你就可以使用標准解析器讀取它(返回)。
例如:
import json
def save(list):
with open("UPCList.txt", "w") as file:
json.dump(list, file)
# file.write('%s\n' % UPCsave)
def load():
with open("UPCList.txt", "r") as file:
return json.load(file)
筆記:
%s
)。 因此我們不得不在閱讀時替換雙引號。也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.