脚本在cx\u freez之后无法检测到文件中的汉字

2024-10-01 04:53:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不同的问题,但它们彼此密切相关:

1)我的python脚本将原始代码文件复制到另一个文件中,并逐行读取(utf-8),用regex检测汉字并将其发送到google translate,得到答案,在包含汉字的行之后用翻译编写另一个文件。当我直接在windows下运行脚本时,这在pycharm下非常有效。但是在用cx\u freeze转换成可执行文件后,它基本上读取文件,但看不到任何中文字符,因此没有翻译完成了。可以你能帮忙吗?你知道吗

2)可执行文件在其他一些计算机(windows)上工作。我发现它与windows-系统区域设置有很强的关系。设置为中文后,我们可以使它工作。我试图通过按区域设置模块的脚本来更改它,但没有成功。你知道吗

以下是可能有助于理解问题的代码片段:

def initialize(self):
    #several imports here
    #several filename operations here

    writefileF = codecs.open(writefile, "w", "utf-8")

    # copy the original to another with  utf-8 encoding (to be safe)
    with io.open(self.orig_filename, ) as source:
            with io.open(readFileN, mode='w', encoding='utf-8') as target:
                try:
                    shutil.copyfileobj(source, target)
                except:
                    print 'trying single copy file with no metadata.. '
                    shutil.copyfile(self.filename, readFileN)
   readFile = codecs.open(readFileN, "r", "utf-8")
   # generAtor func call
   creategen = self.readfilebylines(readFile)
   for iterator in creategen:
       endd = myconcat.join(iterator[0])
       writefileF.writelines(myconcat.join(endd))

def readfilebylines(self, myfileobj):
    linenum = 0
    for lines in myfileobj.readlines():            
        mygen = lines
        mymatch = self.regularexpmatch(lines)
        if mymatch:
            print 'chinese word detected'
            #do translation
        else:
            pass
        yield mygen, linenum

def regularexpmatch(self, mytext):
    chinese_compile = re.compile(ur'[\u4e00-\u9fff]+')
    matched = chinese_compile.search(mytext)
    return matched

Tags: 文件代码self脚本可执行文件windowsdefwith
1条回答
网友
1楼 · 发布于 2024-10-01 04:53:26

我挣扎了几个小时终于找到了解决办法。问题是,如果不指定原始文件编码,脚本就无法更改文件编码。你知道吗

所以就我而言:

def copyfile_inUTF8(self,orig_file,copy_file):
    import chardet
    raw_data=open(orig_file,'r').read()
    target_en='utf-8'
    #detect sourcefile encoding
    orig_en=chardet.detect(raw_data)['encoding']
    print 'original file encoding:',orig_en
    target = open(copy_file, "w")
    target.write(unicode(raw_data, orig_en).encode(target_en))
    print 'copy file encoding:',chardet.detect(open(copy_file,'r').read())['encoding']

使用这个函数,我可以看到原始编码,并将其更改为目标编码,即utf-8。你知道吗

相关问题 更多 >