【问题标题】:Read Word from a Unicode Line instead of Char从 Unicode Line 而不是 Char 读取 Word
【发布时间】:2015-02-16 03:52:56
【问题描述】:

我有以下代码:

for line in contentText:
          print type(line), #-> o/p is unicode
          word = line.strip().split()
          print word, #-> o/p is <type 'list'>
          print type(word),

当我执行line.strip().split() 时,每个字符都会显示出来。

例如,如果我的行是“Read Word from a Unicode Line instead of Char”,那么 o/p 是: R e 一个 d

w ○ r d

一个 . . 以此类推

我想将其读取为“读取”、“单词”,从单词中读取,而不是按字符读取以进行进一步处理..

我怎样才能做到这一点?

另外,我如何删除空格以进行进一步处理?

【问题讨论】:

  • 这个for i in line.strip().split(): print i 为我工作。

标签: python string python-2.7 unicode


【解决方案1】:

迭代字符串产生单字符字符串:

>>> text = 'Read word'
>>> for x in text:
...     print x
... 
R
e
a
d

w
o
r
d

先拆分得到单词列表,然后迭代列表:

>>> text.split()  # str.split remove space characters
['Read', 'word']

>>> for x in text.split():
...     print x
... 
Read
word

【讨论】:

  • 所以基本上你是在要求我在 contentText 中添加“for line?”
  • 否;如果contentText 是一个字符串,而不是字符串列表,则根本不要循环它。
  • @tripleee 我是新手,在这里有点困惑。所以你说的是 contentText 是一个字符串。因此,在该字符串中存储了整行:“从 Unicode 行而不是字符中读取单词”是一个字符串,如果我遍历它,它将单独读取每个字符 R e a d,但不是作为单词读取单词。所以为此我拆分并根据空格拆分?
  • @Dinakar,你理解的没错。这就是我在答案中所说的。
猜你喜欢
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
相关资源
最近更新 更多