如何根据输入正确替换文本文件中的数据



我有以下问题。我试图根据性别的输入来替换这个名字。如果有人能帮助改进我的代码,我将不胜感激。

文本文件(duedate.txt(:

用户:Tommy

性别:男

到期日期:2020-02-18

到目前为止我的代码是:

with open f = ('duedate.txt).read()
z = input("Please select gender to change) 
zz = input("Please select new name")
if z == 'female' 
line.startswith('User'): 
field, value = line.split(:) 
value = zz
print (zz) 

我知道代码不是100%正确的,但如果选择Jessica作为名称,输出应该是:

用户:Jessica

性别:女性

到期日期:2020-02-18

这应该可以工作。注释中给出了代码解释:


import pandas as pd
import numpy as np
# Read the text file into a dataframe
df = pd.read_csv('duedate.txt', sep = "n",header=None)
# Do dataframe manipulations
df[['Variable','Value']] = df[0].str.split(':',expand=True)
del df[0]
# Collect inputs from user:
z = input("Please select gender to change")
zz = input("Please select new name")
# modify dataframe based on user inputs
df.loc[0,"Value"]=zz
df.loc[1,"Value"]=z
#Construct output column
df["Output"] = df["Variable"] + ": " + df["Value"] + "n"
# Save the file back to disk
np.savetxt(r'duedate.txt', df["Output"].values,fmt='%s')

相关内容

  • 没有找到相关文章

最新更新