Python/Java中文乱码的问题

一、python

1.代码中含中文运行时报错

 解决方案: 在文件的顶部添加

#coding:utf-8

2.链接数据库中文乱码

解决方案,在设置链接时指定编码

self.conn = pymssql.connect(host=host, port=port, user=user, password=pwd, database=db, charset="utf8")

3.读取文件中的中文会乱码

解决方案:先获取文件的编码方式,然后解码

(1)获取文件编码方式的代码如下,需要先安装chardet模块
import chardet

# 获取文件的编码方式def getFileCoding(filePath): f = open(filePath, 'r') data = f.read() f.close() return chardet.detect(data).get("encoding")



(2)取用的时候按照编码方式decode

'''读取txt文件中含关键字的行,以列表形式返回'''
def readTxtToList(filePath, keywordList=[]):
    contentList = []
    file = open(filePath)
    lines = file.readlines()
    codingMode = getFileCoding(filePath)
    # 将文本内容读取出来放进列表contens,每一行作为一个元素
    for line in lines:
        if len(line) and not line.startswith("#"):
            if len(keywordList) > 0:
                for keyword in keywordList:
                    if line.find(keyword, 0) >= 0:
                        contentList.append(line.replace("\n", "").decode(codingMode))
            else:
                contentList.append(line.replace("\n", "").decode(codingMode))
    return contentList

4.url中含中文需要编码,待补充


二、java

1.发送请求时,请求的url中含中文,但请求URL中的中文是编码的,如果编码方式是GBK

url = "http://xxx.xx?menuName ="+ URLEncoder.encode("中文部分", "GBK")


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值