我的檔案 text.txt 包含以下內容:
hello my
name is
jack black
and I
eat food
我正在嘗試將此檔案讀入名為 、 等的 2D串列arr中。我是 Python 新手,所以我還不想使用 numpy(我在很多類似的問題中都看到了這一點)。arr[0][0] = helloarr[0][1] = my
這是我到目前為止撰寫的部分代碼:
for x in range(5):
for y in range(2):
nextLine = my_file.readline()
nextLine = line.strip()
arr[x][y]= [nextLine.split('\t')]
print(arr[0][0])
print(arr[0][1])
但是,當我列印arr[0][0]和arr[0][1]. 我得到以下資訊:
[['hello my']]
[['name is']]
拆分“你好”和“我的”的最佳方法是什么,以便每個人在同一行中正確地進入二維串列?
uj5u.com熱心網友回復:
不要使用行數。只需閱讀直到檔案為空。并.strip回傳一個串列;你不需要把它放在另一個串列中。
arr = []
for line in my_file:
arr.append( nextLine.strip().split() )
print(arr[0][0])
print(arr[0][1])
uj5u.com熱心網友回復:
檔案物件在作為生成器迭代時會產生行,因此您可以將檔案物件映射到str.split方法并使用結果序列構造一個串列:
arr = list(map(str.split, my_file))
uj5u.com熱心網友回復:
當我們這樣做
text=open("text.txt","r")
print(text.readlines())
我們得到回應
['hello my\n', 'name is\n', 'jack black\n', 'and I\n', 'eat food']
由于我們正在制作一個二維陣列,我們的第一個索引將用于該行,我們的第二個索引將用于該行中的特定單詞。
text=open("text.txt","r")
wordArray=[]
allText=text.readlines()
for line in allText:
lineArray=[]
allWords=line.replace("\n","").split(" ")
for word in allWords:
lineArray.append(word)
wordArray.append(lineArray)
print(wordArray)```
This will remove the \n's which cause a new line in the text file and then we split the words where there are spaces and append the words by line.
Hope this helps!
uj5u.com熱心網友回復:
with open("text.txt") as f:
lines = f.readlines()
arr = [l.strip().split(" ") for l in lines]
uj5u.com熱心網友回復:
我會使用 pandas 來讀取檔案并將列作為陣列訪問。查看兩個操作的 pandas 檔案: pd.read_csv()和df 列
df = pd.read_csv('input.txt', sep=" ", header=None, names=["a", "b"])
df["a"] # This is your array
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511784.html
