簡體   English   中英

如何將 Python 文件中的字符串數字轉換為整數?

[英]How to change the string numbers into integers from a file in Python?

# writeFile() method is used to open the same file in write mode.
# This is used in order to over write the file.
# Then it traverses through the dictionary and writes all items to the file.
def writeFile():
    file = open("Stocks.txt","w")        
    for stock in stocks:
        file.write(stock+" "+str(stocks[stock])+"\n")
    file.close()

# Program starts here.
# We open the file "Stocks.txt" in read mode.
file = open("Stocks.txt","r")
# Instead of using lists we can store the data in the dictionary.
# We have initialized a dictionary named stocks.
stocks = {}
# Now we traverse through the file line by line.
for line in file:
    # The line must be in the format of Apple 10
    # So we split this line into 2 parts the name and the quantity.
    # split() returns the splitted words as an list.
    # The first part gives name and second part gives quantity.
    #  We type cast the second part into integer data type.
    name = line.split(" ")[0]
    qty = int(line.split(" ")[1])
    # If the name already exists in the dictionary then we add the quantity to the existing quantity.
    if name in stocks.keys():
        stocks[name]+=qty
        # And we call the writeFile() function
        writeFile()
    # If the name doesn't exist then we add it to the dictionary.
    else:
        stocks[name] = qty

# After reading the file we prompt the user if they want to add any other items.
while True:
    cont = input("Do you want to add stocks ? (Y/N)")
    # If user enters N which means no then it exists the loop.
    if(cont=='N'):
        break
    # else asks the user name of the item and the quantity.
    else:
        name = input("Enter the item name: ")
        qty = int(input("Enter the quantity: "))
        # If it already exists then we just add the quantity to the existing quantity.
        if name in stocks.keys():
            stocks[name]+=qty
        # else we add it to the dictionary.
        else:
            stocks[name] = qty
        # Then we call the writeFile method
        writeFile()

該程序需要打開一個包含物品庫存的文件。 這僅適用於文件“Apple 10”中的項目是這樣的,但它們在文件“Key Lime Pie 20”中是這樣的。 那么如何獲取它以便將字符串數字更改為整數呢?

與其在空格上拆分行,不如使用正則表達式在任何數字字符上拆分字符串。

您仍然可以使用 split,但執行以下操作:

 re.split('\d', line)

您可以使用正則表達式刪除所有符號

s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
s = re.sub(r'[^\w]', ' ', s)
print(s)

>>>how much for the maple syrup   20 99  That s ridiculous  '

使用空格拆分然后使用str.isdigit() function 檢查它是否是數字

def getint(x):
    return x.isdigit()

a = [i for i in s.split(' ') if getint(i)]
print(a)
>>> ['20', '99']

如果您非常確定句子中只有一個 integer,只需調用int(a[0])

如果您需要所有這些數字,只需迭代

你仍然可以改進這個答案

暫無
暫無

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

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