![](/img/trans.png)
[英]"Space" get's lost when I copy-paste from Excel in to Python Shell
[英]Ideas for manual copy-paste from excel to python code in spyder
我經常使用 excel 工作表,我只想將其中的一個特定數字列復制到我的 python 腳本中以進行繪圖。 這必須手動完成,因為它始終是不同的文件、列和行。
要使用 numpy arrays,我需要帶有尾隨逗號的數據以這種方式創建 python 數組(我必須添加空格,否則 stackexchange 會將其發布在
myArray=np.array([
1,
2,
3,
4,
6
)]
因此,在使用 excel 中的數字復制列之后,我必須手動添加逗號。 如果我有很多數據,我將在 Excel 中添加一列,在其中添加所有逗號並將數字與逗號一起復制。 但是我覺得應該有更好的方法來做到這一點。
你們知道 python 可能會在沒有逗號的情況下吞下我的數據的方式嗎? 例如
myData = someFunction(
1
2
3
4
6
)
或者你有另一個想法如何更優雅地添加逗號? 我正在使用帶有 Python 3 的 Spyder。
謝謝!
編輯:如果要求是復制一列或一行而不是網格。 下面的in_
可與 replace 一起使用以生成逗號分隔的字符串。
# First copy a column from a spread sheet to the clipboard.
# in_() will return the values separated by newlines '\n'.
# replace these by comma
in_()
# Out[21]: '3\n13\n23\n33\n43\n53\n63\n73\n83\n93\n103\n113\n123\n'
in_().replace('\n', ',')
# Out: '3,13,23,33,43,53,63,73,83,93,103,113,123,'
# If copying a row the copied separator is tab '\t'
# Copy a row in a spreadsheet
in_()
# Out: '60\t61\t62\t63\t64\t65\t66\t67\t68\n'
in_().replace('\t', ',')[:-1] # [-1] removes the newline character.
# Out[25]: '60,61,62,63,64,65,66,67,6'
我編寫了in_()
和from_grid()
將數據從電子表格復制到我想在 python 終端中使用的變量中。 它們允許用戶將電子表格中的區域復制到剪貼板。 in_()
將剪輯作為字符串返回。 from_grid()
將返回這個轉換為字符串列表的列表。
import tkinter as tk
import numpy as np
def in_():
"""
Returns the contents of the clipboard as text.
Usage: txt = in_()
"""
clip=tk.Tk()
clip.withdraw()
temp=clip.selection_get(selection="CLIPBOARD")
clip.destroy()
return temp
def from_grid(delimit_row="\n", delimit_cell="\t"):
"""
Returns a list of lists copied from the clipboard.
Usage: grid=from_grid(delimit_row="\t", delimit_cell="\n")
grid is a list of lists
[ [ r00, r01, r02, ... ],
[ r10, r11, r12, ... ],
....
]
by defaut: the row delimiter is a newline, "\n"
the cell delimiter is a tab character, "\t"
This will paste a copied region of a spreadsheet into a list of lists.
"""
txt=in_()
rows=txt.split(delimit_row)
ret=[]
for row in rows:
temp=row.split(delimit_cell)
ret.append(temp)
return ret[:-1] # A final empty last row is appended.
# This loses it.
import numpy as np
def to_floats( data ):
result= []
for row in data:
temp = []
for item in row:
temp.append(float(item))
result.append(temp)
return np.array(result)
arr = to_floats( from_grid() )
這並不完全符合您的要求,但提供了一種將電子表格數據放入 python 的方法,可以在其中進行處理。
在 python 控制台中運行此程序將讓用戶打印結果,然后可以將其復制到腳本中。
可能有更簡潔的方法來做到這一點。 周圍有一些圖書館,Pyperclip 就是其中之一,但我從未使用過它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.