如何在python中删除字符串中的b前缀?

时间:2017-01-29 08:03:56

标签: python

我正在导入的一堆推文在他们阅读时遇到了这个问题

b'I posted a new photo to Facebook'

我收集b表示它是一个字节。但这证明是有问题的,因为在我最终编写的CSV文件中,b并没有消失,并且干扰了未来的代码。

是否有一种简单的方法可以从我的文本行中删除此b前缀?

请记住,我似乎需要在utf-8或tweepy中编码的文本无法从网络中提取它们。

以下是我正在分析的链接内容:

https://www.dropbox.com/s/sjmsbuhrghj7abt/new_tweets.txt?dl=0

new_tweets = 'content in the link'

代码尝试

outtweets = [[tweet.text.encode("utf-8").decode("utf-8")] for tweet in new_tweets]
print(outtweets)

错误

UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-21-6019064596bf> in <module>()
      1 for screen_name in user_list:
----> 2     get_all_tweets(screen_name,"instance file")

<ipython-input-19-e473b4771186> in get_all_tweets(screen_name, mode)
     99             with open(os.path.join(save_location,'%s.instance' % screen_name), 'w') as f:
    100                 writer = csv.writer(f)
--> 101                 writer.writerows(outtweets)
    102         else:
    103             with open(os.path.join(save_location,'%s.csv' % screen_name), 'w') as f:

C:\Users\Stan Shunpike\Anaconda3\lib\encodings\cp1252.py in encode(self, input, final)
     17 class IncrementalEncoder(codecs.IncrementalEncoder):
     18     def encode(self, input, final=False):
---> 19         return codecs.charmap_encode(input,self.errors,encoding_table)[0]
     20 
     21 class IncrementalDecoder(codecs.IncrementalDecoder):

UnicodeEncodeError: 'charmap' codec can't encode characters in position 64-65: character maps to <undefined>

8 个答案:

答案 0 :(得分:55)

您需要decode bytes您想要一个字符串:

b = b'1234'
print(b.decode('utf-8'))  # '1234'

答案 1 :(得分:9)

只是让您知道您要打印的对象不是字符串,而是字节对象作为字节文字。人们以不完整的方式解释这一点,所以这是我的看法。

考虑通过键入字节文字来创建字节对象(字面上定义字节对象而不实际使用字节对象,例如键入b&#39;&#39;)并将其转换为< strong>字符串对象以utf-8编码。 (请注意,此处的转换意味着解码

byte_object= b"test" # byte object by literally typing characters
print(byte_object) # Prints b'test'
print(byte_object.decode('utf8')) # Prints "test" without quotations

您看到我们只是应用.decode(utf8)函数。

Python中的字节

https://docs.python.org/3.3/library/stdtypes.html#bytes

字符串文字由以下词法定义描述:

https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals

stringliteral   ::=  [stringprefix](shortstring | longstring)
stringprefix    ::=  "r" | "u" | "R" | "U"
shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::=  shortstringchar | stringescapeseq
longstringitem  ::=  longstringchar | stringescapeseq
shortstringchar ::=  <any source character except "\" or newline or the quote>
longstringchar  ::=  <any source character except "\">
stringescapeseq ::=  "\" <any source character>

bytesliteral   ::=  bytesprefix(shortbytes | longbytes)
bytesprefix    ::=  "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes     ::=  "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes      ::=  "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::=  shortbyteschar | bytesescapeseq
longbytesitem  ::=  longbyteschar | bytesescapeseq
shortbyteschar ::=  <any ASCII character except "\" or newline or the quote>
longbyteschar  ::=  <any ASCII character except "\">
bytesescapeseq ::=  "\" <any ASCII character>

答案 2 :(得分:4)

您需要对其进行解码才能将其转换为字符串。在这里查看答案 about bytes literal in python3

In [1]: b'I posted a new photo to Facebook'.decode('utf-8')
Out[1]: 'I posted a new photo to Facebook'

答案 3 :(得分:1)

我通过使用utf-8编码输出来完成它。 这是代码示例

new_tweets = api.GetUserTimeline(screen_name = user,count=200)
result = new_tweets[0]
try: text = result.text
except: text = ''

with open(file_name, 'a', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(text)

即:从api收集数据时不进行编码,仅对输出(打印或写入)进行编码。

答案 4 :(得分:1)

在使用django 2.0的python 3.6上,对字节文字的解码不能按预期工作。 是的,当我打印它时,我得到了正确的结果,但即使你正确打印它,b'值仍然存在。

这就是im编码

uid': urlsafe_base64_encode(force_bytes(user.pk)),

这就是即时解码:

uid = force_text(urlsafe_base64_decode(uidb64))

这就是django 2.0所说的:

urlsafe_base64_encode(s)[source]

在base64中对字节串进行编码,以便在URL中使用,剥去任何尾随等号。

urlsafe_base64_decode(s)[source]

解码base64编码的字符串,添加可能已被剥离的任何尾随等号。

这是我的account_activation_email_test.html文件

{% autoescape off %}
Hi {{ user.username }},

Please click on the link below to confirm your registration:

http://{{ domain }}{% url 'accounts:activate' uidb64=uid token=token %}
{% endautoescape %}

这是我的主机响应:

Content-Type:text / plain;字符集= “UTF-8” MIME版本:1.0 内容传输编码:7位 主题:激活您的MySite帐户 来自:webmaster @ localhost 致:testuser@yahoo.com 日期:星期五,2018年4月20日06:26:46 -0000 消息ID:&lt; 152420560682.16725.4597194169307598579@Dash-U>

嗨testuser,

请点击以下链接确认您的注册:

http://127.0.0.1:8000/activate/b'MjU'/4vi-fasdtRf2db2989413ba/

,您可以看到uid = b'MjU'

预期uid = MjU

在控制台中测试:

$ python
Python 3.6.4 (default, Apr  7 2018, 00:45:33) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
>>> from django.utils.encoding import force_bytes, force_text
>>> var1=urlsafe_base64_encode(force_bytes(3))
>>> print(var1)
b'Mw'
>>> print(var1.decode())
Mw
>>> 

经过调查,它似乎与python 3有关。 我的解决方法非常简单:

'uid': user.pk,

我在激活功能上以uidb64的形式收到它:

user = User.objects.get(pk=uidb64)

瞧:

Content-Transfer-Encoding: 7bit
Subject: Activate Your MySite Account
From: webmaster@localhost
To: testuser@yahoo.com
Date: Fri, 20 Apr 2018 20:44:46 -0000
Message-ID: <152425708646.11228.13738465662759110946@Dash-U>


Hi testuser,

Please click on the link below to confirm your registration:

http://127.0.0.1:8000/activate/45/4vi-3895fbb6b74016ad1882/

现在它运作正常。 :)

答案 5 :(得分:1)

****如何删除python ****中已解码字符串的b''字符

import base64
a='cm9vdA=='
b=base64.b64decode(a).decode('utf-8')
print(b)

答案 6 :(得分:0)

假设您不想像其他人在这里建议的那样立即再次对其进行解码,则可以将其解析为字符串,然后仅剥离开头的'b和结尾的'

>>> x = "Hi there ?" 
>>> x = "Hi there ?".encode("utf-8") 
>>> x
b"Hi there \xef\xbf\xbd"
>>> str(x)[2:-1]
"Hi there \\xef\\xbf\\xbd"   

答案 7 :(得分:-3)

虽然这个问题已经很久了,但我认为对于谁来面对同样的问题可能会有所帮助。这里的文本是如下字符串:

text= "b'I posted a new photo to Facebook'"

因此,您无法通过编码来删除b,因为它不是一个字节。我做了以下删除它。

cleaned_text = text.split("b'")[1]

将提供"I posted a new photo to Facebook"