推 lajji: 用冒號當分隔符存成csv? 01/30 12:20
推 TitanEric: 你把名字放進name list之後 在下一段應該是講話內容 01/30 13:27
→ TitanEric: 所以你就 Name.pop() 可以把上一個放進的名字拿出來 01/30 13:28
→ TitanEric: 當然 應該用一個變數去存上一個名字就可以 不用list 01/30 13:28
兩位高手的建議因為文件結構應該無法運行,把冒號當分隔符取出發言者沒問題,
但是發言內容可能會有很多行。假設我資料的第一行是 「小明:」,然後接下來的
八行都是小明發言的內容,然後再下一行(第十行)是「小華:」,然後接下來的五行
都是小華的發言內容,我的問題是,我應該怎樣讓電腦知道,在讀完第九行之後,
創建一個list如["小明","八行內容"],然後再讀取剩下的六行,然後在最後創立一個
list為["小華","五行內容"]。謝謝!
※ 編輯: TZULIU (168.150.122.93), 01/30/2019 14:21:08
推 highpower: 當某行出現冒號時,就表示新的發言者出現 01/30 15:08
推 yangs0618: 那請問一下會有一句話講完沒換行直接出現另個名字嗎 01/30 19:01
推 yangs0618: 如果一個人講完一定換行 可以用到if “:” in line: 01/30 19:03
→ yangs0618: 暫存的text append進sentence else: text.extend(line) 01/30 19:04
推 TitanEric: 樓上方法記句子 另一個變數記名字 遇到名字丟進list 01/31 00:48
→ nini200: 只用:判斷 後面不同人的發言 沒法分類正確吧? 01/31 01:29
推 nini200: 大致上有寫出來了 給你參考 01/31 05:18
→ nini200: 先找出所有說話者 重複的用集合去掉 01/31 05:19
→ nini200: 我的方法 A陣列儲存要的名字行號B陣列儲存非要的名字行號 01/31 05:21
→ nini200: C陣列將AB陣列合併例A=[0,9]B=[3,6,11]C=[0,3,6,9,11,16] 01/31 05:24
→ nini200: 0-3 9-11就是要的內容 C陣列16是最後一行 01/31 05:28
→ nini200: 打錯 B陣列儲存非要名字含冒號的行號 01/31 05:29
→ nini200: 我的方法比較麻煩 有更好方法煩請告知 01/31 05:37
推 jasonfghx: WOW 01/31 09:50
感謝各位先進的幫忙,我昨晚和今天早上又想了一下加問了一下朋友,
以下是我現在的作法(有點笨但是對於我這種非高手比較容易理解):
##先讀取文件的每一行並建立一個list
##同時也創建一個index
file = open('文件', 'r')
All_lines = []
Names = []
length = 0
#Read all lines in the text file
for line in file:
if "Column" not in line:
line = re.sub(r"(\d+\.?)", "", line)
line = line.strip()
if not line:
continue
else:
All_lines.append(line.strip())
length += 1
else:
continue
##以新建的list作為新文件並且抓取發言者及其發言並結何為一sub list
for i in range(length):
temp = []
if All_lines[i].find(':') != -1:
#Split the name
#Let's split the line into an array called "tokens" using the ":" as a separator:
tokens = All_lines[i].split(":")
#and let's extract the data:
temp.append(tokens[0])
j = i + 1
while j < length and All_lines[j].find(':') == -1:
#All_lines[j] = re.sub(r" ", "", All_lines[j])
temp.append(All_lines[j].strip())
j += 1
Names.append(temp)
還請各位高手賜教,謝謝!
※ 編輯: TZULIU (168.150.122.93), 01/31/2019 13:45:20
推 nini200: 謝謝分享 01/31 21:12
推 lemon651: 幹麻那麼麻煩 就用你原本的方法不好嗎? 直接用一個空字 02/01 11:02
→ lemon651: 串不停的加就好了阿 02/01 11:02
推 lemon651: 遇到冒號就append字串 再append名字 然後字串加後面的li 02/01 11:04
→ lemon651: ne 再遇到冒號之前不停的加 缺點就是第一格會是空字串 02/01 11:05
→ lemon651: 但是remove掉就好了 用deque的話可以省remove掉的時間 02/01 11:05