我需要将(在Python中)一个4字节的char转换为其他字符.这是将其插入到我的UTF-8 mysql数据库没有得到一个错误,如:"不正确的字符串值:在第1行'\ XF0\x9F\X94\x8E’列'线’"
通过向mysql插入4字节unicode引发的警告显示这样做:
>>> import re
>>> highpoints = re.compile(u'[\U00010000-\U0010ffff]')
>>> example = u'Some example text with a sleepy face: \U0001f62a'
>>> highpoints.sub(u'', example)
u'Some example text with a sleepy face: '
Run Code Online (Sandbox Code Playgroud)
但是,我得到了与评论中的用户相同的错误,"...字符范围很差.."这显然是因为我的Python是UCS-2(而不是UCS-4)版本.但后来我不知道该怎么做呢?
我有一个带有第一行unicode字符的文本文件和ASCII中的所有其他行.我尝试将第一行读作一个变量,将所有其他行读作另一个变量.但是,当我使用以下代码时:
# -*- coding: utf-8 -*-
import codecs
import os
filename = '1.txt'
f = codecs.open(filename, 'r3', encoding='utf-8')
print f
names_f = f.readline().split(' ')
data_f = f.readlines()
print len(names_f)
print len(data_f)
f.close()
print 'And now for something completely differerent:'
g = open(filename, 'r')
names_g = g.readline().split(' ')
print g
data_g = g.readlines()
print len(names_g)
print len(data_g)
g.close()
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
<open file '1.txt', mode 'rb' at 0x01235230>
28
7
And now for something completely differerent:
<open file '1.txt', mode 'r' at 0x017875A0> …Run Code Online (Sandbox Code Playgroud) 鉴于重音的unicode字样u'??????',我需要剥离acute(u'?????'),并将重音格式更改为u'???+??',其中'+'代表前一个字母的锐角.
我现在所做的是使用一个有效且无法完成符号的字典:
accented_list = [u'??', u'??', u'??', u'??', u'??', u'??', u'??', u'??', u'??']
regular_list = [u'?', u'?', u'?', u'?', u'?', u'?', u'?', u'?', u'?']
accent_dict = dict(zip(accented_list, regular_list))
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情:
def changeAccentFormat(word):
for letter in accent_dict:
if letter in word:
its_index = word.index(letter)
word = word[:its_index + 1] + u'+' + word[its_index + 1:]
return word
Run Code Online (Sandbox Code Playgroud)
但是,它当然不能按预期工作.我注意到这段代码:
>>> word = u'??????'
>>> for letter in word:
... print letter
Run Code Online (Sandbox Code Playgroud)
给
?
?
? …Run Code Online (Sandbox Code Playgroud) 如何确定Python 3.x中Unicode字符串的显示宽度,以及是否有一种方法可以使用该信息将这些字符串与对齐str.format()?
激励示例:将字符串表打印到控制台。一些字符串包含非ASCII字符。
>>> for title in d.keys():
>>> print("{:<20} | {}".format(title, d[title]))
zootehni- | zooteh.
zootekni- | zootek.
zoothe?que | zooth.
zooveterinar- | zoovet.
zoovetinstitut- | zoovetinst.
? | ??
>>> s = 'e?'
>>> len(s)
2
>>> [ord(c) for c in s]
[101, 768]
>>> unicodedata.name(s[1])
'COMBINING GRAVE ACCENT'
>>> s2 = '?'
>>> len(s2)
1
Run Code Online (Sandbox Code Playgroud)
可以看出,str.format()仅将字符串(len(s))中代码点的数量作为宽度,导致输出中的列偏斜。搜索该unicodedata模块,没有发现任何建议的解决方案。
Unicode规范化可以解决è的问题,但不能解决亚洲字符(通常显示宽度更大)的问题。类似地,存在零宽度的unicode字符(例如,零宽度的空间用于允许单词内的换行符)。您无法使用规范化解决这些问题,因此请不要建议“规范化字符串”。
编辑:添加了有关规范化的信息。
编辑2:在我的原始数据集中,也有一些欧洲组合字符,即使标准化后也不会导致单个代码点:
zwemwater | zwemw.
zwia?z- | zw. …Run Code Online (Sandbox Code Playgroud) 在Python 2.7中:
In [2]: utf8_str = '\xf0\x9f\x91\x8d'
In [3]: print(utf8_str)
In [4]: unicode_str = utf8_str.decode('utf-8')
In [5]: print(unicode_str)
In [6]: unicode_str
Out[6]: u'\U0001f44d'
In [7]: len(unicode_str)
Out[7]: 2
Run Code Online (Sandbox Code Playgroud)
由于unicode_str只包含一个unicode代码点(0x0001f44d),为什么len(unicode_str)返回2而不是1?
我想从TripAdvisor推出阿姆斯特丹500家餐厅的名单; 然而,在第308家餐厅后,我收到以下错误:
Traceback (most recent call last):
File "C:/Users/dtrinh/PycharmProjects/TripAdvisorData/LinkPull-HK.py", line 43, in <module>
writer.writerow(rest_array)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 6: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我尝试了一些我在StackOverflow上找到的东西,但是现在没有任何工作.我想知道是否有人可以查看我的代码并看到任何可能的解决方案.
for item in soup2.findAll('div', attrs={'class', 'title'}):
if 'Cuisine' in item.text:
item.text.strip()
content = item.findNext('div', attrs=('class', 'content'))
cuisine_type = content.text.encode('utf8', 'ignore').strip().split(r'\xa0')
rest_array = [account_name, rest_address, postcode, phonenumber, cuisine_type]
#print rest_array
with open('ListingsPull-Amsterdam.csv', 'a') as file:
writer = csv.writer(file)
writer.writerow(rest_array)
break
Run Code Online (Sandbox Code Playgroud) 我是张量流和神经网络的新手.我开始了一个关于检测波斯文本错误的项目.我使用了这个地址中的代码并在这里开发了代码.请检查代码,因为我无法在此处输入所有代码.
我想要做的是给模型提供几个波斯句子进行训练,然后看模型是否可以检测到错误的句子.该模型适用于英语数据,但当我将其用于波斯数据时,我遇到了这个问题.
代码太长了,无法写在这里,所以我试着指出我认为可能导致问题的部分.我使用这些行train.py很好地工作并存储词汇表:
x_text, y = data_helpers.load_data_labels(datasets)
# Build vocabulary
max_document_length = max([len(x.split(" ")) for x in x_text])
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
x = np.array(list(vocab_processor.fit_transform(x_text)))
Run Code Online (Sandbox Code Playgroud)
但是在训练之后我尝试使用以下代码eval.py:
vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab")
vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
x_test = np.array(list(vocab_processor.transform(x_raw)))
Run Code Online (Sandbox Code Playgroud)
发生此错误:
vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\contrib\learn\python\learn\preprocessing\text.py", line 226, in restore
return pickle.loads(f.read())
File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 118, in read
self._preread_check()
File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 78, in _preread_check
compat.as_bytes(self.__name), 1024 * 512, status)
File "C:\WinPython-64bit-3.5.2.3Qt5\python-3.5.2.amd64\lib\contextlib.py", line 66, in __exit__ …Run Code Online (Sandbox Code Playgroud) 我有这样的功能:
persian_numbers = '??????????'
english_numbers = '1234567890'
arabic_numbers = '??????????'
english_trans = string.maketrans(english_numbers, persian_numbers)
arabic_trans = string.maketrans(arabic_numbers, persian_numbers)
text.translate(english_trans)
text.translate(arabic_trans)
Run Code Online (Sandbox Code Playgroud)
我希望它将所有阿拉伯语和英语数字翻译成波斯语.但Python说:
english_translate = string.maketrans(english_numbers, persian_numbers)
ValueError: maketrans arguments must have same length
Run Code Online (Sandbox Code Playgroud)
我试图用Unicode编码字符串,utf-8但我总是遇到一些错误!有时问题是阿拉伯字符串而不是!你知道更好的解决方案吗?
似乎问题是ASCII中的Unicode字符长度.像'?'这样的阿拉伯数字 是两个角色 - 我发现了ord().长度问题从这里开始:-(
我一直在尝试运行此代码,这是错误
File "C:/hari/Academics/python/py programs/gui qt4/book/calculator.py", line 27, in updateUi
text = unicode(self.lineedit.text(),'utf-8')
NameError: name 'unicode' is not defined
Run Code Online (Sandbox Code Playgroud)
代码 :
from __future__ import division
from math import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class Form(QDialog):
def __init__(self,parent =None):
super(Form,self).__init__(parent)
self.browser =QTextBrowser()
self.lineedit =QLineEdit("type an exp")
self.lineedit.selectAll()
layout=QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi)
self.setWindowTitle("Calculate")
def updateUi(self):
try:
text = unicode(self.lineedit.text())
print(type(text))
self.browser.append(text+" = <b>"+eval(text)+"</b>" )
except:
self.browser.append("<font color=red>"+ text + " is invalid</font>")
app=QApplication(sys.argv) …Run Code Online (Sandbox Code Playgroud) 假设我有一个UTF-8 str,例如
my_str = "??????" # ['?', '?', '?', '?', '?', '?']
Run Code Online (Sandbox Code Playgroud)
我如何找到其中包含多少个字母?len(my_str)返回6,即包含的Unicode代码点数。实际上是4个字母长。
还有一个额外的问题:有些语言将有向图定义为单个字母(例如,“ Dh”是现代阿尔巴尼亚字母的第6个字母),我该如何处理这种边缘情况?
python-unicode ×10
python ×9
python-2.7 ×4
unicode ×4
codec ×1
file-io ×1
mysql ×1
pyqt4 ×1
python-3.4 ×1
string ×1
tensorflow ×1
utf-8 ×1
web-scraping ×1
width ×1