You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DM-Script与Python中多字节字符串编解码问题求助

多字节字符在DM-Script与Python交互中的编码问题

我的文件路径或文本中包含多字节字符,读取时出现异常。已知最优方案是避免使用多字节字符,但当前Windows系统默认编码为Shift-JIS(非UTF-8),而Python默认编码为UTF-8,二者存在编码冲突。

以下是针对"shift-jis.txt"和"utf-8.txt"(内容相同、编码不同)的测试代码:

DM-Script测试代码

TagGroup txtTg(string filepath,number encoding)
{
    string text
    TagGroup TextInFileTg=NewTagList()
    number fileID=OpenFileForReading(filepath)
    while(ReadFileLine(fileID,encoding,text))
    {
        TextInFileTg.TagGroupInsertTagAsString(infinity(),text)
    }
    CloseFile(fileID)
    return TextInFileTg
}

string dirpath="C:\\Users\\arksa\\Documents\\scripts"

TagGroup flistTg=GetFilesInDirectory(dirpath,1)
string ext="txt"
string fname,fpath,text
number fileID
TagGroup fTg=NewTagGroup()
number encoding
for(number i=0;i<flistTg.TagGroupCountTags();i++)
{
    flistTg.TagGroupGetTagAsString("["+i+"]:Name",fname)
    fpath=PathConcatenate(dirpath,fname)
    if(fname.PathExtractExtension(0)==ext)
    {
        if(fname=="shift-jis.txt")
        {
            encoding=0
            fTg.TagGroupSetTagAsTagGroup("DM can read "+fname,txtTg(fpath,encoding))
        }
        if(fname=="utf-8.txt")
        {
            for(number j=0;j<3;j++)
            {
                encoding=j
                fTg.TagGroupSetTagAsTagGroup("DM cannot read "+fname+":"+"encoding="+encoding,txtTg(fpath,encoding))
            }
        }
    }
}

fTg.TagGroupOpenBrowserWindow("text",0)

Python测试代码

import DigitalMicrograph as DM
import os

dirpath=r'C:\Users\arksa\Documents\scripts'
files=['shift-jis.txt','utf-8.txt']
encodings=['shift-jis','utf-8']

tag=DM.NewTagGroup()
for i in range(len(files)):
    path=os.path.join(dirpath,files[i])
    ftag=DM.NewTagList()
    with open(path,encoding=encodings[i]) as f:
        for fline in f:
            ftag.InsertTagAsString(-1,str(fline).encode('shift-jis').decode('utf-8','backslashreplace'))
            #print(fline)
    tag.SetTagAsTagGroup("writing strings in "+files[i]+" to tag group from python fails.",ftag)

tag.OpenBrowserWindow(True)

测试结果

  • DM-Script可正确读取Shift-JIS编码文件,但无法读取UTF-8文件
  • Python可读取两种编码文件,但将字符串写入DM TagGroup时失败

当前困境:仅当多字节字符编码与Windows系统编码(Shift-JIS)一致时,DM-Script才能正确处理,且找不到支持指定编码写入TagGroup的函数,求解决方法。

内容的提问来源于stack exchange,提问作者arksakura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 09:46:29