【问题标题】:exclude unicode from split() of db.get result从 db.get 结果的 split() 中排除 unicode
【发布时间】:2016-05-16 17:36:38
【问题描述】:

x.split() 下面的结果是我想要的,因为结果中没有 unicode。

server:~ brian$ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'M Y'
>>> x.split()
['M', 'Y']

但在我使用db.get 的应用程序中,choices 的结果是[u'M', u'Y'],而不是'choices' = 'M Y'

def post(self, blog_id):
        blog = db.get(db.Key.from_path('Blogs', blog_id))
    n = Reminders(parent=blog, purpose=self.request.get('purpose'),
                  choices=self.request.get('choices').split())
        n.put()

我怎样才能得到我想要的结果?

这个问题与另一个问题不同,因为 google-app-engine 或 python2.7 似乎在被拆分的序列的每个元素周围强制使用 u''。我也尝试过使用.encode('ascii','ignore'),但无济于事。

【问题讨论】:

  • 这对您的程序有何影响?...因为我认为建议处理 unicode 字符串,并且由于您正在处理 Python2.7,因此很自然会得到 u'M'u'Y' 作为输出...因为它们在您的 db 对象中被视为 unicode 字符串。
  • 在我看来您正在使用 GAE DB?...我错了吗?
  • 它会影响我的程序,因为我想将结果作为参数/参数之一包含到 javascript 函数中。 js 函数因该参数而窒息。我一直fiddling with it here 如果你去那里,试着双击“M”。然后将函数的输入更改为包含 u'。

标签: python


【解决方案1】:

尝试使用encode函数。

例子:

In [1]: x= u'M Y'

In [2]: x
Out[2]: u'M Y'

In [3]: x.split()
Out[3]: [u'M', u'Y']

In [4]: x.encode('utf8').split()
Out[4]: ['M', 'Y']

在您的代码中,在拆分之前添加encode 函数:

n = Reminders(parent=blog, purpose=self.request.get('purpose'),
     choices=self.request.get('choices').encode('utf8').split())

【讨论】:

  • 这看起来很有希望,但行不通。我什至尝试以不同的方式放置 .encode('utf8') 或使用更多括号,但要么得到仍然包含 u' 的相同结果,要么得到列表没有 .split()s 的错误消息。
  • 在这种情况下,您可能想要执行n=[s.encode('utf8') for s in Reminders(parent=blog, purpose=self.request.get('purpose'), choices=self.request.get('choices').encode('utf8').split())] 之类的操作,它将采用以前的 unicode 列表并创建一个没有 u 的新列表
  • 我收到错误TypeError: 'Reminders' object is not iterable
  • Reminders 似乎是您自己实现的一个类。在这种情况下,您必须使其可迭代。为此,您应该实现__iter__ 函数和next 函数。欲了解更多信息,请查看this question的答案
  • 这听起来可能是一个不错的选择。如果您查看问题本身的 cmets,Iron Fist 建议 Reminders 是 GAE 数据库模型的一部分。尽管我忽略了确认 Iron Fist 的“建议”,但它是正确的,并且我的代码包括 class Reminders(db.Model):。所以我不确定在这种情况下是否可以实现__iter__ 函数。无论如何,就目前而言,正如您通过看到我的“答案”所知道的那样,我已经完全回避了这个问题。
【解决方案2】:

在我的情况下,答案很简单,只需在 javascript 中而不是在 python 中执行 split()。这样u'...'s 就永远不会生成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2012-04-28
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多