導航:首頁 > 編程語言 > pythondicttofile

pythondicttofile

發布時間:2022-11-01 19:04:53

python_merge file

您安好.
----------------------------
# File : warmup.py

def lines_starts_with(f, s):
____"""Return a list containing the lines of the given open file that start with
____the given str. Exclude leading and trailing whitespace.
____
____Arguments:
____- `f`: the file
____- `s`: str at the beginning of the line
____"""
____result = []
____for line in f:
________if line.startswith(s):
____________result.append(line.strip())
____return result

def file_to_dictionary(f, s):
____"""Given an open file that contains a unique string followed by a given
____string delimiter and more text on each line, return a dictionary that
____contains an entry for each line in the file: the unique string as the key
____and the rest of the text as the value (excluding the delimiter, and leading
____and trailing whitespace).
____
____Arguments:
____- `f`: the file
____- `s`: the delimiter str
____"""
____result = {}
____for line in f:
________k, _, v = line.partition(s)
________result[k.strip()] = v.strip()
____return result

def merge_dictionaries(d1, d2):
____"""Return a dictionary that is the result of merging the two given
____dictionaries. In the new dictionary, the values should be lists. If a key is
____in both of the given dictionaries, the value in the new dictionary should
____contain both of the values from the given dictionaries, even if they are the
____same.
____merge_dictionaries({ 1 : 'a', 2 : 9, -8 : 'w'}, {2 : 7, 'x' : 3, 1 : 'a'})
____should return {1 : ['a', 'a'], 2 : [9, 7], -8 : ['w'], 'x' : [3]}
____Arguments:
____- `d1`, 'd2': dicts to be merged
____"""
____result = {}
____for key in d1:
________if key in d2:
____________result[key] = [d1[key], d2[key]]
________else:
____________result[key] = [d1[key]]
____for key in d2:
________if not key in result:
____________result[key] = [d2[key]]
____return result

-----------------------------------------------------
# File fasta.py

from warmup import *

def count_sequences(f):
____"""Return the number of FASTA sequences in the given open file. Each
____sequence begins with a single line that starts with >.
____
____Arguments:
____- `f`: the file
____"""
____return len(lines_starts_with(f, '>'))

def get_sequence_list(f):
____"""Return a nested list where each element is a 2-element list containing a
____FASTA header and a FASTA sequence from the given open file (both strs).
____
____Arguments:
____- `f`: the file
____"""
____result = []
____current_key = ''
____current_data = ''
____for line in f:
________if line.startswith('>'):
____________if current_data:
________________result.append([current_key, current_data])
________________current_data = ''
____________current_key = line.strip()
________else:
____________current_data+= line.strip()
____result.append([current_key, current_data])
____return result

____
def merge_files(f1, f2):
____"""Return a nested list containing every unique FASTA header and sequence
____pair from the two open input files. Each element of the list to be returned
____is a 2-element list containing a FASTA header and a FASTA sequence.
____
____Arguments:
____- `f1`, 'f2': The File
____"""
____seq = get_sequence_list(f1) + get_sequence_list(f2)
____seq = list( set(seq) )
____return seq

def get_codons(s):
____"""Return a list of strings containing the codons in the given DNA sequence.
____
____Arguments:
____- `s`: DNA sequence, divied by 3
____"""
____return [s[3*i : 3*(i+1)] for i in xrange(len(s)/3)]

def get_amino_name_dict(f):
____"""Return a dictionary constructed from the given open file, where the keys
____are amino acid codes and the values are the amino acid names.
____
____Arguments:
____- `f`: the file, like amino_names.txt
____"""
____return file_to_dictionary(f, ' ')

def get_codon_amino_dict(f):
____"""Return a dictionary where the keys are codons and the values are amino
____acid codes from the given open file.
____
____Arguments:
____- `f`: the file, like codon_aminos.txt
____"""
____return file_to_dictionary(f, ':')

def translate(s, d):
____"""Return the given DNA sequence (the str parameter) translated into its
____amino acid codes, according to the given dictionary where the keys are
____codons and the values are amino acid codes. You may assume that the length
____of the string is divisible by 3.
____
____Arguments:
____- `s`: given DNA sequence
____- `d`: given dictionary
____"""
____codons = get_codons(s)
____result = []
____for i in codes:
________result.append(d[i])
____return result

def codon_to_name(s, d1, d2):
____"""Return the name of the amino acid for the given codon (the str
____parameter).
____
____Arguments:
____- `s`: given codon
____- `d1`: codons for keys and amino acid codes for values
____- `d2`: amino acid codes for keys and name for values
____"""
____return d2[d1[s]]

② 【Python】淺談python中的json

一 前言  

   最近一直在做開發相關的工作--基於Django的web 平台,其中需要從model層傳輸數據到view 層做數據展示或者做業務邏輯處理。我們採用通用的Json格式--Json(JavaScript Object Notation) 是一種輕量級的數據交換格式,易於閱讀和程序解析。

二 認識Json

   2.1 Json 結構

   常見的Json格式為 「名稱/值」對的集合,其中 值可以是對象,列表,字典,字元串等等。比如

backup_data = {"back_to_host": "dbbk0",

"ip_address": "10.10.20.3",

"host_name": "rac4",

"port": 3306}

  2.2 使用Json

  Python的Json模塊序列化與反序列化的過程分別是 編碼和解碼。這兩個過程涉及到兩組不同的函數

  編碼 把一個Python對象編碼轉換成Json字元串,json.mps(data)/json.mp(data,file_handler)

  解碼 把Json格式字元串解碼轉換成Python對象,json.loads(data)/json.load(file_handler)

  在python中要使用Json模塊做相關操作,必須先導入:

import Json

  2.3 主要函數

  編碼函數主要有 json.mps(data)/json.mp(data,file_handler)

   json.mps()的參數是將python對象轉換為字元串,如使用json.mps序列化的對象json_mps=json.mps({'a':1, 'b':2}) ,json_mps='{"b": 2, "a": 1}'

   json.mp 是將內置類型序列化為json對象後寫入文件。

 解碼函數主要由json.loads(data)/json.load(file_handler)  

    json.loads的參數是內存對象,把Json格式字元串解碼轉換成Python對象,json_loads=json.loads(d_json)  #{ b": 2, "a": 1},使用load重新反序列化為dict

    json.load()的參數針對文件句柄,比如本地有一個文件/tmp/test.json  json_load=json.load(open('/tmp/test.json'))

具體案例參考如下:

In [3]: data={"back_to_host": "rac1",

...: "ip_address": "10.215.20.3",

...: "host_name": "rac3",

...: "port": 3306}

In [7]: json_str=json.mps(data)

In [8]: print json_str

{"ip_address": "10.215.20.3", "back_to_host": "rac1", "host_name": "rac3", "port": 3306}

In [9]: json_loads=json.load(json_str)

---------------------------------------------------------------------------

AttributeError Traceback (most recent call last)

<ipython-input-9-180506f16431> in <mole>()

----> 1 json_loads=json.load(json_str)

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.pyc in load(fp, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)

284

285 ""

注意 從上面的報錯信息來看 json.loads 傳參是字元串類型,並不是文件句柄,沒有 read()屬性。

In [10]: json_loads=json.loads(json_str)

In [11]: print json_loads

{u'back_to_host': u'rac1', u'ip_address': u'10.215.20.3', u'host_name': u'rac3', u'port': 3306}

In [12]: type(json_loads)

Out[12]: dict

In [13]: type(json_str)

Out[13]: str

利用mp 將數據寫入 mp.json

In [17]: with open('/tmp/mp.json','w') as f:

...: json.mp(json_str,f)

...:

yangyiDBA:~ yangyi$ cat /tmp/mp.json

"{\"ip_address\": \"10.10.20.3\", \"back_to_host\": \"rac1\", \"host_name\": \"rac3\", \"port\": 3306}"

yangyiDBA:~ yangyi$

利用json.load 將mp.sjon的數據讀出來並賦值給 data 

In [18]: with open('/tmp/mp.json','r') as f:

...: data=json.load(f)

...:

In [19]: print data

{"ip_address": "10.10.20.3", "back_to_host": "rac1", "host_name": "rac3", "port": 3306}

三 小結

  本文算是一篇學習筆記,主要對比了json.loads/json.load  , json.mps/ json.mp 的使用差異 ,方便以後更好的使用json 。

以上為本次分享內容,感謝觀看。

③ python 讀取CSV 文件

讀取一個CSV 文件

最全的

一個簡化版本

filepath_or_buffer : str,pathlib。str, pathlib.Path, py._path.local.LocalPath or any object with a read() method (such as a file handle or StringIO)

可以是URL,可用URL類型包括:http, ftp, s3和文件。對於多文件正在准備中

本地文件讀取實例:://localhost/path/to/table.csv

**sep **: str, default 『,』

指定分隔符。如果不指定參數,則會嘗試使用逗號分隔。分隔符長於一個字元並且不是『s+』,將使用python的語法分析器。並且忽略數據中的逗號。正則表達式例子:' '

**delimiter **: str, default None

定界符,備選分隔符(如果指定該參數,則sep參數失效)

delim_whitespace : boolean, default False.

指定空格(例如』 『或者』 『)是否作為分隔符使用,等效於設定sep='s+'。如果這個參數設定為Ture那麼delimiter 參數失效。

在新版本0.18.1支持

header : int or list of ints, default 『infer』

指定行數用來作為列名,數據開始行數。如果文件中沒有列名,則默認為0,否則設置為None。如果明確設定header=0 就會替換掉原來存在列名。header參數可以是一個list例如:[0,1,3],這個list表示將文件中的這些行作為列標題(意味著每一列有多個標題),介於中間的行將被忽略掉。

注意:如果skip_blank_lines=True 那麼header參數忽略注釋行和空行,所以header=0表示第一行數據而不是文件的第一行。

**names **: array-like, default None

用於結果的列名列表,如果數據文件中沒有列標題行,就需要執行header=None。默認列表中不能出現重復,除非設定參數mangle_pe_cols=True。

index_col : int or sequence or False, default None

用作行索引的列編號或者列名,如果給定一個序列則有多個行索引。

如果文件不規則,行尾有分隔符,則可以設定index_col=False 來是的pandas不適用第一列作為行索引。

usecols : array-like, default None

返回一個數據子集,該列表中的值必須可以對應到文件中的位置(數字可以對應到指定的列)或者是字元傳為文件中的列名。例如:usecols有效參數可能是 [0,1,2]或者是 [『foo』, 『bar』, 『baz』]。使用這個參數可以加快載入速度並降低內存消耗。

as_recarray : boolean, default False

不贊成使用:該參數會在未來版本移除。請使用pd.read_csv(...).to_records()替代。

返回一個Numpy的recarray來替代DataFrame。如果該參數設定為True。將會優先squeeze參數使用。並且行索引將不再可用,索引列也將被忽略。

**squeeze **: boolean, default False

如果文件值包含一列,則返回一個Series

**prefix **: str, default None

在沒有列標題時,給列添加前綴。例如:添加『X』 成為 X0, X1, ...

**mangle_pe_cols **: boolean, default True

重復的列,將『X』...』X』表示為『X.0』...』X.N』。如果設定為false則會將所有重名列覆蓋。

dtype : Type name or dict of column -> type, default None

每列數據的數據類型。例如 {『a』: np.float64, 『b』: np.int32}

**engine **: {『c』, 『python』}, optional

Parser engine to use. The C engine is faster while the python engine is currently more feature-complete.

使用的分析引擎。可以選擇C或者是python。C引擎快但是Python引擎功能更加完備。

converters : dict, default None

列轉換函數的字典。key可以是列名或者列的序號。

true_values : list, default None

Values to consider as True

false_values : list, default None

Values to consider as False

**skipinitialspace **: boolean, default False

忽略分隔符後的空白(默認為False,即不忽略).

skiprows : list-like or integer, default None

需要忽略的行數(從文件開始處算起),或需要跳過的行號列表(從0開始)。

skipfooter : int, default 0

從文件尾部開始忽略。 (c引擎不支持)

skip_footer : int, default 0

不推薦使用:建議使用skipfooter ,功能一樣。

nrows : int, default None

需要讀取的行數(從文件頭開始算起)。

na_values : scalar, str, list-like, or dict, default None

一組用於替換NA/NaN的值。如果傳參,需要制定特定列的空值。默認為『1.#IND』, 『1.#QNAN』, 『N/A』, 『NA』, 『NULL』, 『NaN』, 『nan』`.

**keep_default_na **: bool, default True

如果指定na_values參數,並且keep_default_na=False,那麼默認的NaN將被覆蓋,否則添加。

**na_filter **: boolean, default True

是否檢查丟失值(空字元串或者是空值)。對於大文件來說數據集中沒有空值,設定na_filter=False可以提升讀取速度。

verbose : boolean, default False

是否列印各種解析器的輸出信息,例如:「非數值列中缺失值的數量」等。

skip_blank_lines : boolean, default True

如果為True,則跳過空行;否則記為NaN。

**parse_dates **: boolean or list of ints or names or list of lists or dict, default False

infer_datetime_format : boolean, default False

如果設定為True並且parse_dates 可用,那麼pandas將嘗試轉換為日期類型,如果可以轉換,轉換方法並解析。在某些情況下會快5~10倍。

**keep_date_col **: boolean, default False

如果連接多列解析日期,則保持參與連接的列。默認為False。

date_parser : function, default None

用於解析日期的函數,默認使用dateutil.parser.parser來做轉換。Pandas嘗試使用三種不同的方式解析,如果遇到問題則使用下一種方式。

1.使用一個或者多個arrays(由parse_dates指定)作為參數;

2.連接指定多列字元串作為一個列作為參數;

3.每行調用一次date_parser函數來解析一個或者多個字元串(由parse_dates指定)作為參數。

**dayfirst **: boolean, default False

DD/MM格式的日期類型

**iterator **: boolean, default False

返回一個TextFileReader 對象,以便逐塊處理文件。

chunksize : int, default None

文件塊的大小, See IO Tools docs for more information on iterator and chunksize.

compression : {『infer』, 『gzip』, 『bz2』, 『zip』, 『xz』, None}, default 『infer』

直接使用磁碟上的壓縮文件。如果使用infer參數,則使用 gzip, bz2, zip或者解壓文件名中以『.gz』, 『.bz2』, 『.zip』, or 『xz』這些為後綴的文件,否則不解壓。如果使用zip,那麼ZIP包中國必須只包含一個文件。設置為None則不解壓。

新版本0.18.1版本支持zip和xz解壓

thousands : str, default None

千分位分割符,如「,」或者「."

decimal : str, default 『.』

字元中的小數點 (例如:歐洲數據使用』,『).

float_precision : string, default None

Specifies which converter the C engine should use for floating-point values. The options are None for the ordinary converter, high for the high-precision converter, and round_trip for the round-trip converter.

指定

**lineterminator **: str (length 1), default None

行分割符,只在C解析器下使用。

**quotechar **: str (length 1), optional

引號,用作標識開始和解釋的字元,引號內的分割符將被忽略。

quoting : int or csv.QUOTE_* instance, default 0

控制csv中的引號常量。可選 QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3)

doublequote : boolean, default True

雙引號,當單引號已經被定義,並且quoting 參數不是QUOTE_NONE的時候,使用雙引號表示引號內的元素作為一個元素使用。

escapechar : str (length 1), default None

當quoting 為QUOTE_NONE時,指定一個字元使的不受分隔符限值。

comment : str, default None

標識著多餘的行不被解析。如果該字元出現在行首,這一行將被全部忽略。這個參數只能是一個字元,空行(就像skip_blank_lines=True)注釋行被header和skiprows忽略一樣。例如如果指定comment='#' 解析『#empty a,b,c 1,2,3』 以header=0 那麼返回結果將是以』a,b,c'作為header。

encoding : str, default None

指定字元集類型,通常指定為'utf-8'. List of Python standard encodings

dialect : str or csv.Dialect instance, default None

如果沒有指定特定的語言,如果sep大於一個字元則忽略。具體查看csv.Dialect 文檔

tupleize_cols : boolean, default False

Leave a list of tuples on columns as is (default is to convert to a Multi Index on the columns)

error_bad_lines : boolean, default True

如果一行包含太多的列,那麼默認不會返回DataFrame ,如果設置成false,那麼會將改行剔除(只能在C解析器下使用)。

warn_bad_lines : boolean, default True

如果error_bad_lines =False,並且warn_bad_lines =True 那麼所有的「bad lines」將會被輸出(只能在C解析器下使用)。

**low_memory **: boolean, default True

分塊載入到內存,再低內存消耗中解析。但是可能出現類型混淆。確保類型不被混淆需要設置為False。或者使用dtype 參數指定類型。注意使用chunksize 或者iterator 參數分塊讀入會將整個文件讀入到一個Dataframe,而忽略類型(只能在C解析器中有效)

**buffer_lines **: int, default None

不推薦使用,這個參數將會在未來版本移除,因為他的值在解析器中不推薦使用

compact_ints : boolean, default False

不推薦使用,這個參數將會在未來版本移除

如果設置compact_ints=True ,那麼任何有整數類型構成的列將被按照最小的整數類型存儲,是否有符號將取決於use_unsigned 參數

use_unsigned : boolean, default False

不推薦使用:這個參數將會在未來版本移除

如果整數列被壓縮(i.e. compact_ints=True),指定被壓縮的列是有符號還是無符號的。

memory_map : boolean, default False

如果使用的文件在內存內,那麼直接map文件使用。使用這種方式可以避免文件再次進行IO操作。

ref:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

④ 基於python的自動駕駛交通牌指示燈識別程序代碼

摘要 def __init__(self, **kwargs):

閱讀全文

與pythondicttofile相關的資料

熱點內容
微盟程序員老婆 瀏覽:928
intellij創建java 瀏覽:110
java連接odbc 瀏覽:38
啟動修復無法修復電腦命令提示符 瀏覽:359
手機編程是什麼 瀏覽:97
山東移動程序員 瀏覽:163
蘇州java程序員培訓學校 瀏覽:475
單片機液晶驅動 瀏覽:854
魔拆app里能拆到什麼 瀏覽:130
新預演算法的立法理念 瀏覽:144
wdcpphp的路徑 瀏覽:134
單片機p0口電阻 瀏覽:926
瀏覽器中調簡訊文件夾 瀏覽:594
五菱宏光空調壓縮機 瀏覽:68
為什麼app佔用幾百兆 瀏覽:680
自動解壓失敗叫我聯系客服 瀏覽:484
易語言新手源碼 瀏覽:456
oa伺服器必須有固定ip地址 瀏覽:45
傳奇源碼分析是什麼 瀏覽:269
解放壓縮機支架 瀏覽:255