所以下面的代碼在 csv 檔案中查找包含關鍵字的行,$$n[]:或者$$n[<characters>]:如果代碼有這些,它將是 anote并且這個注釋將與它上面text的(沒有$$n:or的行$$n[<characters>]: keyword)匹配。我想創建一個pandas data frame顯示匹配texts和注釋的。如果text沒有note附加它,那么它只是一個None值。查看所需結果的預期輸出。
.csv 檔案:
yes hello there
move on to the next command if the previous command was successful.
$$n:describes the '&&' character in the RUN command.
k
$$n[t(a1), mfc(a1,expand,rr)]: description
代碼:
import pandas as pd
import numpy as np
import logging
def _ReadCsv(filename, READ_MODE):
"""
Read CSV file from remote path.
Args:
filename(str): filename to read.
Returns:
The contents of CSV file.
Raises:
ValueError: Unable to read file
"""
data = None
try:
with open(filename, READ_MODE) as fobj:
data = fobj.readlines()
except IOError:
logging.exception('')
if not data:
raise ValueError('No data available')
return data
#Return all the lines from txt file
file1 = _ReadCsv('hello.txt', 'r')
#Keep a record of the Texts and Notes of the txt file
text_note = {'Text': np.array([]), 'Note':np.array([])}
for count,line in enumerate(file1):
"""
Get rid of empty lines
Match each text with a note
If note is empty then give it a value of null
"""
if line.strip():
if line.startswith('$$n:'):
text_note['Note'] = np.append(text_note['Note'], [line.strip()])
else:
text_note['Text'] = np.append(text_note['Text'], [line.strip()])
預期輸出:
---- --------------------------------------------------- ------------------------------------------------
| | Text | Note |
|---- --------------------------------------------------- ------------------------------------------------|
| 0 | yes hello there | None |
| 1 | move on to the next command if the previous co... | describes the && character in the RUN command. |
| 2 | k | description |
---- --------------------------------------------------- ------------------------------------------------
uj5u.com熱心網友回復:
這應該有效:
import re
import pandas as pd
with open('test.csv') as f:
lines = [s.strip() for s in f.read().split('\n') if s]
texts = []
notes = []
for i, line in enumerate(lines):
if re.search(r'\$\$.*\:', line):
notes.append(re.sub(r'\$\$.*\:', '', line).strip())
else:
texts.append(line)
if len(texts) - len(notes) > 1:
notes.append(None)
if len(notes) != len(texts):
notes.append(None)
df = pd.DataFrame({
'Text': texts,
'Note': notes
})
輸出:
Text Note
0 yes hello there None
1 move on to the next command if the previous co... describes the '&&' character in the RUN command.
2 k description
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/504044.html
