一、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")