简体   繁体   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()

This program needs to open a file that contains a stock of items.该程序需要打开一个包含物品库存的文件。 This only works if the items are like this in the file "Apple 10", but they are like this in the file, "Key Lime Pie 20".这仅适用于文件“Apple 10”中的项目是这样的,但它们在文件“Key Lime Pie 20”中是这样的。 So how do I get it so that I can change the string numbers into integers?那么如何获取它以便将字符串数字更改为整数呢?

Rather than splitting the line on spaces, use regex to split the string on any character that is a number.与其在空格上拆分行,不如使用正则表达式在任何数字字符上拆分字符串。

You can still use split, but do something like:您仍然可以使用 split,但执行以下操作:

 re.split('\d', line)

you can remove all the symbols using regex您可以使用正则表达式删除所有符号

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  '

split using space then check if it's digit number using str.isdigit() function使用空格拆分然后使用str.isdigit() function 检查它是否是数字

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

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

if you are pretty sure there will only be one integer on a sentence, just call int(a[0])如果您非常确定句子中只有一个 integer,只需调用int(a[0])

if you need all those numbers, just iterate如果您需要所有这些数字,只需迭代

you still can improve this answer你仍然可以改进这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数字从python中的文件转换为整数 - How to convert numbers to integers from a file in python 如何从 txt 文件中提取字符串(数字)并使用 python 中的正则表达式转换为整数 - How to extract string (numbers) from txt file and convert to integers using regular expressions in python 如何在python中将字符串更改为Integers - How to change string to Integers in python 如果它们在 python 中有标题,我如何从文件中获取数字并将它们作为整数读取? - How do I take numbers from a file and read them as integers if they have headings in python? 从包含素数的文件到 Python 上的整数列表 - From a file containing prime numbers to a list of integers on Python 如何将字典的键值从随机数更改为连续整数? - How to change the key values of dictionary from random numbers to consecutive integers? Python-如何读取文件中带整数但带有标题的数字? - Python - how can i read numbers in a file as integers but with headings? Python - 如何从文件中读取和更改特定字段? (具体来说,数字) - Python — how to read and change specific fields from file? (specifically, numbers) 如何从 Python 中的整数列表中计算素数之和? - How to calculate sum of prime numbers from list of integers in Python? 如何从文件名或字符串中删除所有数字-Python3 - How to remove all numbers from a file name or a string - Python3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM