【问题标题】:python write can take 2 argumentspython write可以接受2个参数
【发布时间】:2012-07-01 07:18:55
【问题描述】:

我有一个问题要制作“output.txt”。 我想将 word 和 prob(l.19) 结果写入 “output.txt”文件。 当我写“model_file.write(word, prob)”时,终端骂我 “TypeError:函数只需要 1 个参数(给定 2 个)”消息。 我试图添加更多参数,但没有奏效.. 有人可以帮我解答我的问题吗?

这是一个字数.PY
total_count = 0 

train_file = open(sys.argv[1],"r")
for line in train_file:
    words =  line.strip().split(" ") 
    words.append("</s>")
    for word in words:t
    counts[word] = counts.get(word, 0) + 1 
    total_count = total_count + 1

model_file = open('output.txt',"w")
for word, count in sorted(counts.items(),reverse=True):
    prob = counts[word]*1.0/total_count
    print "%s --> %f" % (word, prob) 

model_file.write(word, prob)
model_file.close()
#

【问题讨论】:

    标签: python arguments


    【解决方案1】:

    只需简单地替换

    model_file.write(word, prob)

    model_file.write(word+' '+str(prob)+'\n')


    注意write()方法被实现为只有一个字符串参数,所以你必须将prob转换成字符串(通过str()方法)然后组合它用字符串运算符+ 加上word,这样你就只有一个字符串参数。


    P.S.:虽然你没有问这个,但我不得不说,如果你要写每个单词及其概率,你应该把model_file.write(word+' '+str(prob)+'\n')放入for声明。否则,如果您出于某种目的拒绝在for 语句之外调用它,那么您也应该在for 语句之外分配wordprob。否则会导致另一个错误。

    【讨论】:

      【解决方案2】:

      您可以使用print 语句来执行此操作:

      print >>model_file, word, prob
      

      【讨论】:

        【解决方案3】:

        我想创建一种关于我的 df 的描述,所以我写了这个:

        # Create an empty txt
        f = open(os.path.join(pathlib.Path().absolute(),'folder','florder','name.txt'), "a")
        
        # Create an kind of header
        f.write('text'+'\n')
        f.write('text'+'\n')
        f.write("""
        -------------------
        """)
        f.write('text:'+ '\n')
        f.write("""
        """)
        
        
        for c in range(0, len(df.columns)):
                campo = df.columns[c]
                if df[df.columns[c]].dtype== 'object':
                    text= 'Tex'
                outfile = open('name.txt','w')
                f.write('str:'+"'"+str(xxx)+"'"'\n')
                f.write('str:'+ str(str)+'\n')
                f.write('\n')
        f.close()
        

        【讨论】:

          猜你喜欢
          • 2014-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-08
          • 1970-01-01
          • 1970-01-01
          • 2021-05-01
          • 1970-01-01
          相关资源
          最近更新 更多