- 博客(56)
- 资源 (13)
- 收藏
- 关注
原创 python xlwd 设置行高与列宽
文章目录设置行高设置列宽小栗子参考资料设置行高方法一:tall_style = xlwt.easyxf('font:height 720;') # 36ptsheet.row(0).set_style(tall_style) # 设置第1行的行高方法二:sheet.row(4).height_mismatch = True # 设置第5行的行高sheet.row(4).height = 256 * 20设置列宽sheet.col(1).width = 30 * 256 # 设置第2
2021-04-30 11:18:27 1409
原创 python xlwt 解决报错:ValueError: More than 4094 XFs (styles)
解决方案对于设置样式的函数:def define_style(): font = xlwt.Font() font.colour_index = 1 # 初始化样式 my_style = xlwt.XFStyle() my_style.font = font # 设置字体 return my_style写入数据时,不要使用sheet.write(0, 0, '数据', define_style())这种方式,改为:mystyle = define_
2021-04-30 10:56:37 1025
原创 python list根据值返回位置
第一次出现的位置my_list = [1, 2, 3, 5, '6', '6']print(my_list.index('6'))全部的位置my_list = [1, 2, 3, 5, '6', '6']print([i for i, v in enumerate(my_list) if v == '6'])
2021-04-30 09:00:18 4001
原创 xlwt设置excel字体、对齐方式、边框、颜色、背景色
文章目录1.思路2.自定义样式> 字体> 对齐方式> 边框> 颜色> 背景色3.小栗子1.思路首先需要定义一个样式:my_style = xlwt.XFStyle()然后对按照下面字体/对齐方式等设置,设置完成后,赋值给xlwt.XFStyle()的对象,例:# 设置好字体类型font = xlwt.Font()font.name = 'name Times New Roman'然后赋值即可:my_style.font = font2.自定义样式&g
2021-04-30 08:54:15 8243
原创 python使用xlwt创建与保存excel文件
xlwt处理excel的思想是先创建一个excel文件:book,然后创建sheet表:sheet,最后对sheet表内的单元格:cell写入数据。小栗子:import xlwtif __name__ == '__main__': book = xlwt.Workbook(encoding='utf-8') sheet = book.add_sheet('sheet1', cell_overwrite_ok=True) sheet.write(0, 0, u'(0,0)')
2021-04-30 08:29:14 2221 1
原创 python填充数组到指定长度
功能函数def fill_list(my_list: list, length, fill=None): # 使用 fill字符/数字 填充,使得最后的长度为 length if len(my_list) >= length: return my_list else: return my_list + (length - len(my_list)) * [fill]用法def fill_list(my_list: list, length, fi
2021-04-29 15:02:59 4702
原创 python使用random生成不重复的随机数
注:如果直接使用random无法避免生成不重复的随机数,除非使用set,所以换一个思路,在所给的区域的所有数值中选择一定数量的数即可,只要给定的数不存在重复值,那么就不会被选出同样的数。可根据需求修改代码,示例代码如下:random.seed(0) # 确定随机种子random.sample(range(1, 10), 5) # 从1到10中选5个数......
2021-04-27 17:07:15 6337 2
原创 pandas Dataframe/Series 设置保留小数位数
设置小数位数series与dataframe都是一样的,在后面直接.round(num)就可以了import pandas as pdseries = pd.Series([123, 12343.3242])print(series.describe().round(2))打印内容如下:count 2.00mean 6233.16std 8641.07min 123.0025% 3178.0850% 6233
2021-04-27 16:32:06 13428 2
原创 多进程使用wikimedia数据训练word2vec模型
语料库下载:请参考:https://blog.csdn.net/weixin_35757704/article/details/1156141121.训练Word2vec模型代码单单使用gensim库训练word2vec模型的代码请参考:https://blog.csdn.net/weixin_35757704/article/details/1156012712. 剔除停用词主要代码是:def get_stop_words(filepath) -> list: return op
2021-04-27 08:39:35 410
原创 LDA模型训练与得到文本主题、困惑度计算(含可运行案例)
文章目录训练LDA模型困惑度计算得到一段文本的主题全部代码及案例(可直接运行)首先使用gensim库:pip install gensim训练LDA模型import gensim # pip install gensimfrom gensim import corporadef train_lda_model(all_contents, dictionary, num_topic=10): """这是训练LDA的核心方法""" corpus = [dictionary.d
2021-04-25 11:03:56 4652 8
原创 替换掉(取消掉)pip freeze 生成的@ file:///格式,变为正常的==版本号
解决方法1首先安装pipreqs,安装命令:pip install pipreqs因为pipreqs是进入项目的.py文件下汇总import的内容再导出至requirement.txt,因此首先进入项目目录:cd project目录然后在当前目录下运行:pipreqs ./即可生成requirement.txt文件注:这里pipreqs按tab键可能无法提示,但是不会影响运行解决方法2pip list --format=freeze > requirements.txt然
2021-04-25 08:20:46 1380
原创 Python求解多元非线性方程组
使用sympy模块:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ sympy案例import sympydef solve_test(): a, b = sympy.symbols('a b') # 两个未知数 eq1 = a + 2 * b # 等式一: a+2b = 0 eq2 = a * 4 - 5 + b # 等式二:4a-5+b = 0 sol = sympy.solve((eq
2021-04-22 20:11:48 1098 1
原创 pytorch从dataframe中提取信息,变为可训练的tensor
文章目录提取方法步骤1.构造dataframe步骤2. 从dataframe中提取信息步骤3.转变格式案例代码要从dataframe格式的数据中提取数据,然后传入到torch的模型中的方法如下:提取方法步骤1.构造dataframedf = pd.DataFrame(create_float((100, 5))) # 生成50行3列的dataframedf['label'] = create_float((100, 1))步骤2. 从dataframe中提取信息y = df['label'
2021-04-20 16:06:55 4440
原创 pytorch修改tensor数据类型
方法一import torchmy_tensor = torch.randn(2, 4) # 默认为float32类型print("原始:", my_tensor)print('____________________________________________________________')# torch.long() 将tensor投射为long类型long_tensor = my_tensor.long()print(long_tensor)print('________
2021-04-20 15:46:00 20978
原创 Python生成多个浮点数、二维浮点数
代码如下:import numpy as npdef create_float(shape=(1, 1)): return np.array([np.random.random_sample(shape[1]) for i in range(shape[0])])if __name__ == '__main__': float_array = create_float((10, 20)) print(float_array)
2021-04-20 15:15:54 1000
原创 pytorch学习——构建多元线性回归的网络结构
定义网络class LinearRegressionModel(nn.Module): def __init__(self, input_shape, output_shape): super(LinearRegressionModel, self).__init__() # 第一步必须这么写 self.linear = nn.Linear(input_shape, output_shape) def forward(self, x): # 反向传播
2021-04-20 15:00:21 1055 1
原创 Networdx小案例学习
文章目录图的类型无向图小案例有向图的小案例参考资料图的类型无向图小案例import networkx as nximport matplotlib.pyplot as pltG = nx.DiGraph([(0, 1), (1, 2), (2, 3), (1, 3)]) # 构建有向图G.add_edge('A', 'B', weight=3, color='red')# 下面的代码为开始pos = nx.spring_layout(G, k=4) # k:Optimal dis
2021-04-19 15:21:12 187
原创 simpy报错RuntimeError: <Event() object at 0xxxxxx> has already been triggered
RuntimeError: <Event() object at 0xxxxxx> has already been triggered报错原因:已经激活的事件被再次激活,比如:self.test_event = env.event()self.test_event.succeed()self.test_event.succeed()
2021-04-17 22:21:56 117
原创 向量距离汇总(连续值与离散值),Latex与Python实现
文章目录1. 闵可夫斯基距离 Minkowski Distancep=1时 曼哈顿距离 Manhattan Distancep=2时 欧氏距离 Euclidean Distance标准化欧氏距离Standardized Euclidean Distancep->∞ 切比雪夫距离 Chebyshev Distance2.余弦相似度 Cosine Similarity修正余弦相似度 Adjusted Cosine Similarity3.皮尔逊线性相关系数 Pearson Correlation Coef
2021-04-17 22:20:57 1859
原创 Python捕获 Warning 警告
warning在Python中是不会被try except捕获的,所以首先修改它,让try except可以捕获warning:import warningswarnings.filterwarnings('error')然后使用try except包裹代码即可:try: warnings.warn(Warning("AAAAAAAAA"))except Warning: print('This is a warning')...
2021-04-17 17:38:29 3778 3
原创 解决Mac安装LightGBM报错LightGBM and gcc 8 in MacOS: Library not loaded
Github Issue上有一个解决方法,但是博主失败了:https://github.com/Microsoft/LightGBM/issues/1369以下是我的解决方法:博主解决方法首先使用brew安装:brew install libomp然后直接使用pip即可:pip install lightgbm其他人使用conda的解决方法据说使用conda可以直接安装成功,不会报错:conda install --yes --prefix {sys.prefix} -c conda-
2021-04-17 16:35:19 523
原创 Mac brew报错Error: The following directories are not writable by your user: /usr/local/share/man/man5
解决方法sudo chown -R $(whoami) /usr/local/share/man/man5chmod u+w /usr/local/share/man/man5
2021-04-17 16:30:01 801
原创 numpy ndarry格式新增一行,将格式从(k,)变为(k,1)
使用array[:,np.newaxis]即可:import numpy as nparray = np.ones(shape=(20,))print(array.shape) # (20,)array = array[:, np.newaxis]print(array.shape) # (20,1)
2021-04-17 16:15:34 173
原创 解决pytouch导入模型报错:AttributeError: Can‘t get attribute ‘XXX‘ on <module ‘__main__‘ from XXX>
解决方法看到这个报错的文件位置:<module '__main__' from XXX,只需要把自定义的那个模型的类,即Can't get attribute 'XXX'这里的XXX,直接把这个类复制到文件位置这里即可。问题解析使用pytouch导入模型的时候有一个pickle的操作,但是因为未知自定义的模型的结构,所以无法解析模型...
2021-04-16 15:37:44 26515 8
原创 Python使一列数据总和为1
使用案例:import numpy as npdef make_sum_is_one(array:np.ndarray): return array/sum(array)print(make_sum_is_one(np.array([12,3,4,5,6])))
2021-04-15 21:56:07 1581
原创 Numpy计算二维、三维、多维向量空间夹角余弦值
import numpy as npa = np.array([1, 4, 6])b = np.array([-1, 2, -4.3])cos_ab = a.dot(b) / (np.linalg.norm(a) * np.linalg.norm(b))print(cos_ab)
2021-04-15 16:33:33 4869
原创 Python PCA降维小例子
import numpy as npfrom sklearn.decomposition import PCAx = np.array([ [1,2,3,4,5,6], [1,2,3,4,5,56], [3,4,2,34,5,5],])pca = PCA(n_components=2)pca.fit(x)pca.transform(x)
2021-04-15 16:06:54 408
原创 python降维——局部线性嵌入算法(LLE)
sklearn官网地址:https://scikit-learn.org/stable/modules/generated/sklearn.manifold.LocallyLinearEmbedding.html使用案例:import numpy as npfrom sklearn.manifold import LocallyLinearEmbeddingx = np.array([[-3, -1,1,3], [-2, -14,5,6], [-3, -2,1,3]])lle = LocallyL
2021-04-15 12:49:09 796
原创 Gensim word2vec计算多个词之间的相似度
使用most_similar()函数即可,代码如下:from gensim.models import Word2Vecword_model = Word2Vec.load('wiki_word2vec_model') # 导入模型word_model.wv.most_similar(['word','proverb']) # 这个list里可以输入多个词返回结果:[('phrase', 0.7695871591567993), ('verse', 0.6313120126724243),
2021-04-14 09:08:44 2819
原创 Gensim加载word2vec模型与简易使用
二进制文件from gensim.models import KeyedVectorsword_model = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True)word_model.has_index_for('123') # 判断词向量中是否包含 '123'word_model.get_vector('word') # 打印word的向量非二进制文件word_mo
2021-04-14 08:28:59 935
原创 Python去除字符串中的特殊字符(包括空格)
使用方法import redef delete_boring_characters(sentence): return re.sub('[0-9’!"#$%&\'()*+,-./:;<=>?@,。?★、…【】《》?“”‘’![\\]^_`{|}~\s]+', "", sentence)if __name__ == '__main__': clean_str = delete_boring_characters('[Helloworld!!!!]')
2021-04-13 21:36:01 5104
原创 Python多进程读写文件操作
代码:由于进程之间是不通信的,因此这样会打乱顺序:import multiprocessingdef write_in_file(str_line): with open('test.txt', 'a+') as f: line = str(str_line) + "\n" f.write(line)def multiplication(num): print(str(num)) return numif __name__ ==
2021-04-13 18:17:01 954
原创 python代码中使用pip安装文件
以安装pandas为例:from pip._internal import main# pip install pandasmain(['install','pandas'])# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ pandasmain(['install','-i','https://pypi.tuna.tsinghua.edu.cn/simple/','pandas'])
2021-04-13 16:48:49 1012
原创 Python使用pyechart绘制3d散点图
代码import numpy as npimport pyecharts.options as optsfrom pyecharts.charts import Scatter3Dif __name__ == '__main__': a = np.arange(1, 10, 0.1) b = a * 2 + 10 c = a + b # 这里的 data 格式是 [ (x,y,z), (x,y,z), (x,y,z), ........] data = li
2021-04-13 15:35:28 2238
原创 Python NLP英文文本转小写
使用方法如下:def lower_word(all_content): for i, content in enumerate(all_content): all_content[i] = content.lower() # 文本转小写 return all_contentif __name__ == '__main__': print(lower_word(['HELLO WORLD', 'Hello World']))...
2021-04-12 19:41:29 647
原创 NLTK使用英文词性还原
安装NLTK的方法请参考:[https://blog.csdn.net/weixin_35757704/article/details/115629297](https://blog.csdn.net/weixin_35757704/article/details/115629297)# 词性还原 Lemmatization```pyfrom nltk.stem import WordNetLemmatizerdef word_lemmatize(all_content): lemmat
2021-04-12 19:38:18 948
原创 pandas聚合dataframe某一列的值中的所有元素
数据:onetwo0a;b4.21b;c0.032a0使用merge_column()函数即可:import pandas as pddef merge_column(dataframe, column, seq=';') -> set: merge_sentence = set() all_sentences = dataframe[column].values.tolist() for s in all_sent
2021-04-12 18:59:39 1758
原创 离线安装NLTK工具包
以wordnet为例:我想使用wordnet工具包,如果在代码中直接使用工具包会报错:********************************************************************** Resource python-BaseExceptionwordnet not found. Please use the NLTK Downloader to obtain the resource: >>> import nltk >
2021-04-12 17:14:57 1169 2
使用pyLDAvis的实例结果,及d3.min.js,ldavis.v1.0.0.css,ldavis.v1.0.0.js
2022-02-26
handless_firefox.tar
2020-12-26
一键安装libpcap及其所有依赖文件的脚本
2017-11-26
W3Cschool参考手册资料
2017-04-23
空空如也
TA创建的收藏夹 TA关注的收藏夹
TA关注的人