“Replace”将字符串转换为float。如何保持字符串格式?

时间:2017-06-02 10:24:23

标签: python csv

我想从我的twitter文本语料库中删除表情符号和表情符号。 该脚本成功删除了表情符号。但是当我将文件用于下一个分析步骤时,字符串被转换为float,这会在接下来的步骤中导致错误。在不剥离表情符号的情况下,文本不会浮动,并且在下一个分析步骤中不会导致错误。因此,错误可以在此脚本中找到。我可以以某种方式更改脚本,将格式保留为字符串吗?

结果是输出文件中的某些行:

<class 'str'> ""USERNAME Danke, Dir auch, beim Stabilisieren und Herumdoktern am Falschen ""
<class 'str'> ""USERNAME Also ich werde, sobald die Brille da ist, sagen, was ich von den Gläsern und co halte! ""
<class 'float'> nan

#remove emoticons 
with open("data_sentiment.csv","r", encoding="utf-8") as oldfile1, open("data_sentiment_stripped_emoticons.csv", 'w',encoding="utf-8") as newfile1:
    for line in oldfile1:
        line=line.replace("","").replace(":)", "").replace(":D", "").replace(":(","").replace(":-(","")
        newfile1.write(line)
newfile1.close()

1 个答案:

答案 0 :(得分:0)

问题不在此脚本中。此脚本创建一个文本文件,根据定义,该文件不包含浮点数。

问题在于脚本(/ program / whatever)最终会读到你在这里写的文件。第二个脚本将打开文件并遇到类似“2.6”的字符串,然后将其解释为数字。

相关问题