我有这样的功能:
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().长度问题从这里开始:-(
我有一个小脚本,它将提取.zip文件.这很好用,但仅适用于.zip文件,它们的文件名中不包含带有"ä","ö","ü"(等等)字母的文件.否则我收到此错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "threading.pyc", line 552, in __bootstrap_inner
File "install.py", line 92, in run
File "zipfile.pyc", line 962, in extractall
File "zipfile.pyc", line 950, in extract
File "zipfile.pyc", line 979, in _extract_member
File "ntpath.pyc", line 108, in join
UnicodeDecodeError: 'ascii' codec can't decode byte 0x94 in position 32: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
这是我的脚本的提取部分:
zip = zipfile.ZipFile(path1)
zip.extractall(path2)
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?
我一直在尝试运行此代码,这是错误
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个字母),我该如何处理这种边缘情况?
我使用 Pytesseract 对屏幕截图运行大量 OCR。这在大多数情况下运行良好,但少数情况会导致此错误:
pytesseract.image_to_string(image,None, False, "-psm 6")
Pytesseract: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
我正在使用Python 3.4。任何如何防止此错误发生的建议(不仅仅是尝试/例外)都会非常有帮助。
keyAWS S3通知事件中表示文件名的字段是URL转义的.
当文件名包含空格或非ASCII字符时,这很明显.
例如,我已将以下文件名上传到S3:
my file ??????.txt
Run Code Online (Sandbox Code Playgroud)
通知收到:
{
"Records": [
"s3": {
"object": {
"key": u"my+file+%C5%99%C4%9B%C4%85%CE%BB%CE%BB%CF%85.txt"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我试过解码使用:
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
但是产量:
my file ÅÄÄλλÏ.txt
Run Code Online (Sandbox Code Playgroud)
当然,当我尝试使用Boto从S3获取文件时,我收到404错误.
当我在 Python 中使用三引号多行字符串时,我倾向于使用 textwrap.dedent 来保持代码可读性,并具有良好的缩进:
some_string = textwrap.dedent("""
First line
Second line
...
""").strip()
Run Code Online (Sandbox Code Playgroud)
但是,在 Python 3.x 中, textwrap.dedent 似乎不适用于字节字符串。我在为返回长多行字节字符串的方法编写单元测试时遇到了这个问题,例如:
# The function to be tested
def some_function():
return b'Lorem ipsum dolor sit amet\n consectetuer adipiscing elit'
# Unit test
import unittest
import textwrap
class SomeTest(unittest.TestCase):
def test_some_function(self):
self.assertEqual(some_function(), textwrap.dedent(b"""
Lorem ipsum dolor sit amet
consectetuer adipiscing elit
""").strip())
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
在 Python 2.7.10 中,上述代码工作正常,但在 Python 3.4.3 中失败:
some_string = textwrap.dedent("""
First line
Second line
...
""").strip() …Run Code Online (Sandbox Code Playgroud) 我在json文件中有一个1500表情符号字符列表,我想将它们导入我的python代码,我做了一个文件读取并将其转换为python字典,但现在我只有143条记录.如何将所有表情符号导入我的代码,这是我的代码.
import sys
import ast
file = open('emojidescription.json','r').read()
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
emoji_dictionary = ast.literal_eval(file.translate(non_bmp_map))
#word = word.replaceAll(",", " ");
keys = list(emoji_dictionary["emojis"][0].keys())
values = list(emoji_dictionary["emojis"][0].values())
file_write = open('output.txt','a')
print(len(keys))
for i in range(len(keys)):
try:
content = 'word = word.replace("{0}", "{1}")'.format(keys[i],values[i][0])
except Exception as e:
content = 'word = word.replace("{0}", "{1}")'.format(keys[i],'')
#file.write()
#print(keys[i],values[i])
print(content)
file_write.close()
Run Code Online (Sandbox Code Playgroud)
这是我的输入样本
{
"emojis": [
{
"?": ["Graduate"],
"©": ["Copy right"],
"®": ["Registered"],
"??": ["family"],
"?????": ["love"],
"™": ["trademark"],
"???": ["love"],
"?": ["time"], …Run Code Online (Sandbox Code Playgroud) 我需要比较两个字符串。aa从 PDF 文件中提取(使用 pdfminer/chardet)并且bb是键盘输入。如何标准化第一个字符串以进行比较?
>>> aa = "?"
>>> bb = "?"
>>> aa == bb
False
>>>
>>> aa.encode('utf-8')
b'\xc4\x81'
>>> bb.encode('utf-8')
b'a\xcc\x84'
Run Code Online (Sandbox Code Playgroud) 我正在尝试收集波斯语推文并进行文本分析。我用 tweepy 来做到这一点。但结果是unicode格式。如何将 unicode 文本转换为真正的波斯语文本?
\n\n import tweepy\n import csv\n import pandas as pd\n ####input your credentials here\n consumer_key = xxxx\n consumer_secret = xxxx\n access_token = xxxx\n access_token_secret = xxxx\n\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth,wait_on_rate_limit=True)\n #####United Airlines\n # Open/Create a file to append data\n csvFile = open(\'got5.txt\', \'a\')\n #Use csv Writer\n csvWriter = csv.writer(csvFile)\n\n for tweet in tweepy.Cursor(api.search,q="\xda\xaf\xd8\xa7\xd8\xaa", count=5,\n lang="fa",\n since="2017-04-03").items():\ncsvWriter.writerow([tweet.created_at, tweet.text.encode(\'utf-8\')])\nprint([tweet.created_at, tweet.text.encode(\'utf-8\')])\nRun Code Online (Sandbox Code Playgroud)\n\n结果:
\n\n 2019-07-11 17:09:17,b\'@StingTIcon \\xd8\\xa8\\xd8\\xa7\\xd8\\xb2 \\xd8\\xa7\\xdb\\x8c\\xd9\\x86 \\xd8\\xae\\xd9\\x88\\xd8\\xa8\\xd9\\x87 =)))))) \\xd8\\xa7\\xd9\\x88\\xd9\\x86\\xd8\\xa7\\xdb\\x8c\\xdb\\x8c \\xda\\xa9\\xd9\\x87 \\xd9\\x85\\xdb\\x8c\\xda\\xaf\\xd9\\x85 \\xd8\\xaa\\xd8\\xa7\\xd8\\xa8\\xd9\\x84\\xd9\\x88\\xd8\\xaa\\xd8\\xb1\\xdb\\x8c\\xd9\\x86 …Run Code Online (Sandbox Code Playgroud) python-unicode ×10
python ×6
python-3.x ×3
python-2.7 ×2
unicode ×2
utf-8 ×2
amazon-s3 ×1
aws-lambda ×1
emoji ×1
indentation ×1
literals ×1
pyqt4 ×1
python-3.4 ×1
tesseract ×1
tweepy ×1
zip ×1