我一直在字符串中获取位置。我读取了文件的内容
with io.open(testfile, 'r', encoding='utf-8') as f
u2705 Offizielle Kanu00e4le ud83cudde9ud83cuddea ud83cudde6ud83cuddf9 ud83cudde8ud83cuddedn@GET_THIS_STING
我该怎么办?"\u2705"被算作1个字母?那么位置36将是@GET_HIS_STING 的开始
--===EDIT===--我现在可以更好地显示问题所在:
import json
from io import open
line = '{"message":{"message_id":3052,"text":"u2705 Offizielle Kanu00e4le ud83cudde9ud83cuddea ud83cudde6ud83cuddf9 ud83cudde8ud83cudded\n@GET_THIS_STING\n123456789","entities":[{"offset":36,"length":26,"type":"mention"}]}}'
myjson = json.loads(line)
text = myjson.get("message", {}).get("text", None)
print(str(text).encode('utf-8', 'replace').decode())
print("string length: " + str(len(text)))
print(text[36:36+15])
print("-------------")
with open("/home/pi/telegram/phpLogs/test.txt", 'r', encoding='utf-8', errors="surrogateescape") as f:
for line in f:
myjson = json.loads(line)
text = myjson.get("message", {}).get("text", None)
print(text)
print("string length: " + str(len(text)))
print(text[36:36+15])
结果:
✅ Offizielle Kanäle ???? ???? ????
@GET_THIS_STING
123456789
string length: 61
@GET_THIS_STING
-------------
✅ Offizielle Kanäle 🇩🇪 🇦🇹 🇨🇭
@GET_THIS_STING123456789
string length: 54
HIS_STING123456
因此,当我将代码中的字符串(UTF-8(作为变量(string(时,一切都很好。但当我创建一个包含内容的文件并读取它时,
"{"message":{"message_id":3052,"text":"u2705 Offizielle Kanu00e4le ud83cudde9ud83cuddea ud83cudde6ud83cuddf9 ud83cudde8ud83cudded\n@GET_THIS_STING\n123456789","entities":[{"offset":36,"length":26,"type":"mention"}]}}"
我总是收到一个"错误"的结果:(所以读取文件是我的问题,因为之后的字符串不一样——甚至长度也不一样!
如果这个字符串表示@scribe的答案所建议的✅ Offizielle Kanäle 🇩🇪 🇦🇹 🇨🇭
,那么我认为您会遇到这里提到的问题:转换为表情符号
因此,我建议更换
with io.open(testfile, 'r', encoding='utf-8') as f:
text = f.read() # you didn't show it but probably that's what you have done
带有
with open(testfile, 'r', encoding='ascii') as f:
text = json.load(f)
或者,如果文件是"JSON行"而不是单个JSON:
with open(testfile, 'r', encoding='ascii') as f:
for line in f:
text = json.loads(line)
然后text
将是一个合适的Unicode字符串,所以text[36:]
应该能满足您的要求。
如果文件text.txt
确实包含
u2705 Offizielle Kanu00e4le ud83cudde9ud83cuddea ud83cudde6ud83cuddf9 ud83cudde8ud83cuddedn@GET_THIS_STING
尝试:
with open('text.txt', 'r', encoding='utf-8') as f:
str = f.read()
normal_str = ''
i, n = 0, 0
while i < len(str):
if str[i: i + 2] == '\u':
i += 6
normal_str += 'x'
elif str[i: i + 2] == '\n':
i += 2
normal_str += 'x'
else:
normal_str += str[i]
i += 1
n += 1
print(normal_str)
print(normal_str[36:36 + 15])
并且,该输出:
x Offizielle Kanxle xxxx xxxx xxxxx@GET_THIS_STING
@GET_THIS_STING
对于一个看起来像这样的文件text.txt
,
✅ Offizielle Kanäle 🇩🇪 🇦🇹 🇨🇭
@GET_THIS_STING
我们可以,
with open('text.txt', 'r', encoding='utf-8') as f:
str = f.read()
index = str.find('@')
print('char @ is at index: {}'.format(index))
print(str[index:])
它输出
char @ is at index: 30
@GET_THIS_STING