0

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

文本文件(duedate.txt):

用户:汤米

性别:男

截止日期: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 作为名称,输出应该是:

用户:杰西卡

性别女

截止日期:2020-02-18

4

1 回答 1

1

这应该有效。代码解释在注释中给出:


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')
于 2020-02-20T07:51:03.747 回答