Рассмотрим код ниже, который читает текст в myfile.text
, который выглядит следующим образом:
["Author", "Message"]
["littleblackcat", " There's a lot of redditors here that live in the area maybe/hopefully someone saw something. "]
["Kruse", "In other words ,it's basically creating a mini tornado."]
Приведенный ниже код удаляет [
и ]
из text
, а затем разбивает каждую строку в списке строк на ,
, исключая первую строку, которая является заголовком. Некоторые Message
содержат ,
, что вызывает другой столбец (NAN
в противном случае), и, следовательно, код переносит их в одну строку, которая и предназначена.
Код:
with open('myfile.txt', 'r') as my_file:
text = my_file.read()
text = text.replace("[", "")
text = text.replace("]", "")
df = pd.DataFrame({
'Author': [i.split(',')[0] for i in text.split('\n')[1:]],
'Message': [''.join(i.split(',')[1:]) for i in text.split('\n')[1:]]
}).applymap(lambda x: x.replace('"', ''))
Выход:
Author Message
0 littleblackcat There's a lot of redditors here that live in the area maybe/hopefully someone saw something.
1 Kruse In other words it's basically creating a mini tornado.