导航:首页 > 编程语言 > 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相关的资料

热点内容
xp配置java环境变量配置 浏览:7
python中1到100怎么算 浏览:765
小度我想看程序员 浏览:504
bs刷装备建立后文件夹没有 浏览:79
找漫画看应该下载什么app 浏览:182
如何在vps上搭建自己的代理服务器 浏览:744
nginxphp端口 浏览:403
内脏pdf 浏览:152
怎么看云服务器架构 浏览:85
我的世界国际服为什么登不进服务器 浏览:997
微盟程序员老婆 浏览:931
intellij创建java 浏览:111
java连接odbc 浏览:41
启动修复无法修复电脑命令提示符 浏览:360
手机编程是什么 浏览:98
山东移动程序员 浏览:165
苏州java程序员培训学校 浏览:479
单片机液晶驱动 浏览:856
魔拆app里能拆到什么 浏览:132
新预算法的立法理念 浏览:146