Python 编程小问题汇总(一)

1. Python 读取文件编码错误,报错:

UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 23: illegal multibyte sequence

解决方法: 设置 open( ) 方法的 encoding 参数为 utf-8. 即 open(‘text.txt’, encoding=’utf-8’),如果原文件是其他编码则指定为相应的编码。

2. Python 字符串去掉多余的空格和符号

# 去掉两端的
>>>a.strip()
>>>'Hello world'
# 去掉右侧的
>>>a.rstrip()
>>>' Hello world'
# 去掉左侧的
>>>a.lstrip()
>>>'Hello world \n'
# 也可以指定去掉两端的特定内容,例如:
>>>a.rstrip(',') 

3. 由于压缩导致读取的 HTML 文件乱码

如果检测出读取的 HTML 文件是 gzip 格式,可以用以下方法解压缩:

import gzip
def unzip(data):
    unzip_file = gzip.decompress(data)
    return unzip_file

4. 一个去掉字符串中中英文字符的方法

来源:GitHub gumblex

punct = set(u''':!),.:;?]}¢'"、。〉》」』】〕〗〞︰︱︳﹐、﹒ ﹔﹕﹖﹗﹚﹜﹞!),.:;?|}︴︶︸︺︼︾﹀﹂﹄﹏、~¢ 々‖•·ˇˉ―--′’”([{£¥'"‵〈《「『【〔〖([{£¥〝︵︷︹︻ ︽︿﹁﹃﹙﹛﹝({“‘-—_…''')
# 对str/unicode
filterpunt = lambda s: ''.join(filter(lambda x: x not in punct, s))
# 测试
teststr = '在海洋公园泡了一天~人比鱼多多了[汗]随时随地的找人与被人找~~好累[困]我只不过想安静的看看鱼罢了……'
print(filterpunt(teststr))
# 输出:在海洋公园泡了一天人比鱼多多了汗随时随地的找人与被人找好累困我只不过想安静的看看鱼罢了

5. Python 3.6 使用 wordcloud 做中文词云乱码问题

Python 3.6 使用 wordcloud 需要指定 font-path
源码中是这样说的:

font_path : string
Font path to the font that will be used (OTF or TTF). Defaults to DroidSansMono path on a Linux machine. If you are on another OS or don't have this font, you need to adjust this path.

如果不是 Linux 系统需要指定字体所在位置,找到自己系统中字体文件路径就可以了。

# 微软雅黑
my_wordcloud = WordCloud(font_path='C:\Windows\Fonts\msyh.ttf').generate_from_text(text)

6. 筛选出中文字符

也能去掉不需要的符号,英文,数字

import re
def convert_ch(text):
    chinese = re.compile('([\u4e00-\u9fa5]+)+?')
    str_chinese = ''.join(chinese.findall(text))
    return str_chinese
# test
test_str = '在海洋公园泡了一天~人比233鱼多多了[汗]随时随地的找人与被人找~~好累[困]我只不过想安静的看看鱼罢了……Im so happy today'
print(convert_ch(test_str))
# 输出
# 在海洋公园泡了一天人比鱼多多了汗随时随地的找人与被人找好累困我只不过想安静的看看鱼罢了
    原文作者:维吉尼亚加密问题
    原文地址: https://blog.csdn.net/github_36299736/article/details/64904664
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞