I want to make a function that can append a new line of text to a .txt file with if condition.
I’m not good at code. Can someone explain to me how to create a function in python?
ex : given a table like this
| text | similarity | polarity |
|---|---|---|
| ABCDD | 0.6 | POSITIF |
| ASDAS | 0.4 | NEGATIF |
| ASGAS | 1.0 | POSITIF |
So , i want to make a function with if condition. The condition is like this :
If the value in column dataframe [‘similarity’] is greater than 0.5 , and the value in other column dataframe [‘polarity’] is "POSITIF". Then , i want to append a new line of text to a .txt file.
Can someone explain how to make that possible?
I’ve tried myself , but i guess it’s a total mess
if (df['similarity'] > 0.5) & df['polarity'].str.contains('POSITIF').any():
with open("text.txt","a") as myfile:
myfile.write("text appended \n")
>Solution :
It depends what you want to do exactly.
If you need to loop over all the rows, useiterrows (Warning, it is slow!):
with open("text.txt","a") as myfile:
for key, row in df.iterrows():
if (row['similarity'] > 0.5) and ('POSITIF' in row['polarity']):
myfile.write("text appended \n")
If you want to append the line if any row matches both conditions:
if (df['similarity'].gt(0.5) & df['polarity'].str.contains('POSITIF')).any():
with open("text.txt","a") as myfile:
myfile.write("text appended \n")