亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python/Pandas - 通過分隔符將文本拆分為列;并創建一個 csv 文件

Python/Pandas - 通過分隔符將文本拆分為列;并創建一個 csv 文件

鳳凰求蠱 2023-07-18 09:42:51
我有一個很長的文本,其中插入了分隔符“;” 正是我想將文本分成不同列的位置。到目前為止,每當我嘗試將文本拆分為“ID”和“ADText”時,我只得到第一行。然而,兩列中應該有 1439 行/行。我的文字如下所示:1234;寫入的文本包含多個句子,跨越多行,直到某個時刻寫入下一個 ID dwon 2345;然后新的廣告文本開始直到下一個 ID 3456;等等我想使用 ; 將我的文本分成兩列,一列包含 ID,一列包含 AD 文本。#read the text file into python: jobads= pd.read_csv("jobads.txt", header=None)print(jobadsads)#create dataframe df=pd.DataFrame(jobads, index=None, columns=None)type(df)print(df)#name column to target it for split df = df.rename(columns={0:"Job"})print(df)#split it into two columns. Problem: I only get the first row.print(pd.DataFrame(dr.Job.str.split(';',1).tolist(),                   columns=['ID','AD']))不幸的是,這只適用于第一個條目,然后就停止了。輸出如下所示:               ID                                                 AD0            1234                                   text in written from with ...我哪里錯了?我將不勝感激任何建議=)謝謝!
查看完整描述

1 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

示例文本:


FullName;ISO3;ISO1;molecular_weight

Alanine;Ala;A;89.09

Arginine;Arg;R;174.20

Asparagine;Asn;N;132.12

Aspartic_Acid;Asp;D;133.10

Cysteine;Cys;C;121.16

基于“;”創建列 分隔器:


import pandas as pd

f = "aminoacids"

df = pd.read_csv(f,sep=";")

http://img1.sycdn.imooc.com//64b5ee6c000192cd03030163.jpg

編輯:考慮到評論,我認為文本看起來更像是這樣的:


t = """1234; text in written from with multiple sentences going over multiple lines until at some point the next ID is written dwon 2345; then the new Ad-Text begins until the next ID 3456; and so on1234; text in written from with multiple """

在這種情況下,像這樣的正則表達式會將您的字符串拆分為 id 和文本,然后您可以使用它們來生成 pandas 數據框。


import re

r = re.compile("([0-9]+);")

re.split(r,t)

輸出:


['',

 '1234',

 ' text in written from with multiple sentences going over multiple lines until at some point the next ID is written dwon ',

 '2345',

 ' then the new Ad-Text begins until the next ID ',

 '3456',

 ' and so on',

 '1234',

 ' text in written from with multiple ']

編輯2:這是對評論中提問者附加問題的回應: 如何將此字符串轉換為具有 2 列的 pandas 數據框:ID 和文本


import pandas as pd

# a is the output list from the previous part of this answer

# Create list of texts. ::2 takes every other item from a list, starting with the FIRST one.

texts = a[::2][1:] 

print(texts)

# Create list of ID's. ::1 takes every other item from a list, starting with the SECOND one

ids = a[1::2]

print(ids)

df = pd.DataFrame({"IDs":ids,"Texts":texts})


查看完整回答
反對 回復 2023-07-18
  • 1 回答
  • 0 關注
  • 219 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號