[英]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.