您的位置:首页 > 编程语言 > Python开发

python 读取命令参数、导出词向量的几种方式

2018-02-28 23:35 501 查看

Part A. python 读取命令参数的几种方式

一、使用argparse第三方库。(推荐使用) 参考

import argparse # 参数解析库。
parser = argparse.ArgumentParser() # 创建分析器,下面几行是设置分析器的参数有哪些。
parser.add_argument("-i", "--input", type=str, default=None, help="Input word vecs")
parser.add_argument("-l", "--lexicon", type=str, default=None, help="Lexicon file name")
parser.add_argument("-o", "--output", type=str, help="Output word vecs")
parser.add_argument("-n", "--numiter", type=int, default=10, help="Num iterations")
args = parser.parse_args() # 获取参数

wordVecs = read_word_vecs(args.input)# 获取分析器的具体设置过的参数
lexicon = read_lexicon(args.lexicon, wordVecs)
numIter = int(args.numiter)
outFileName = args.output


# 运行。retrofit.py 是上面的代码文件名。
python retrofit.py -i word_vec_file -l lexicon_file -n num_iter -o out_vec_file


二、使用ConfigParser库 参考

import ConfigParser # 配置解析库。需要多生成一份文件,作为配置文件。
class ExperimentRun:
def __init__(self, config_filepath):
self.config = ConfigParser.RawConfigParser() # 初始化,返回类的实例。逐行读取配置文件。
try:
self.config.read(config_filepath) # 开始读取配置文件。
except:
print "Couldn't read config file from", config_filepath
return None

vocabulary_filepath = self.config.get("data", "vocabulary_filepath") # get是返回字符串、getfloat是返回浮点数。
synonym_list = self.config.get("data", "synonyms").replace("[","").replace("]", "").replace(" ", "").split(",")

self.load_experiment_hyperparameters() # 调用下面的函数。
def load_experiment_hyperparameters(self):
self.hyper_k1 = self.config.getfloat("hyperparameters", "hyper_k1")

config_filepath = sys.argv[1] # 读取第2个参数,也就是执行命令的 experiment_parameters.cfg
current_experiment = ExperimentRun(config_filepath)


;TIP: 这份是配置文件。分号开头行会被注释掉的。

[data]

pretrained_vectors_filepath = word_vectors/glove.txt
;pretrained_vectors_filepath = word_vectors/paragram.txt

vocabulary_filepath = linguistic_constraints/vocabulary.txt
synonyms = [linguistic_constraints/ppdb_synonyms .txt, linguistic_constraints/wordnet_synonyms .txt]

[hyperparameters]
hyper_k1 = 0.1


# 运行代码
python counterfitting.py experiment_parameters.cfg # 后面一个是配置文件名,名字后缀是任意的。


Part B. python 导出词向量文件的几种方式

一、print >>可以代替write。使用round限定小数点位数。(推荐使用) 参考

def print_word_vectors(word_vectors, write_path):
"""
This function prints the collection of word vectors to file, in a plain textual format.
"""
print "Saving the counter-fitted word vectors to", write_path, "\n"
with open(write_path, "wb") as f_write:
for key in word_vectors:
print >>f_write, key, " ".join(map(str, numpy.round(word_vectors[key], decimals=6)))


二、直接open后write。用%.f限制小数点位数 。 参考

def print_word_vecs(wordVectors, outFileName):
outFile = open(outFileName, 'w')
for word, values in wordVectors.iteritems():
outFile.write(word+' ')
for val in wordVectors[word]:
outFile.write('%.4f' %(val)+' ')
outFile.write('\n')
outFile.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: