【阅读】NLTK基础教程_用NLTK 和Python库构建机器学习应用 (1)

本文介绍了使用Python的NLTK库进行文本处理的基础知识,包括列表操作、字符串方法、正则表达式以及初步的文本分析。通过示例展示了Python在处理文本时的便利性,如字符串分割、去除空白字符、大小写转换和查找替换等操作。此外,还提及了如何编写函数以及遇到的语法错误和解决方法。
摘要由CSDN通过智能技术生成

上一段书中的实例

>>> lst = [1,2,3,4]
>>> dir(lst)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>>

---------------------------------------------

果然,书中用的是python2,而我用的是python3.6.3,所以输出打印(print)要加括号!!!

>>> print 'First element:' +str(lst[0])
  File "<stdin>", line 1
    print 'First element:' +str(lst[0])
                         ^
SyntaxError: invalid syntax
>>> print('First element:' +str(lst[0]))
First element:1

>>>

-------------------------------

>>> help(lst.index)
Help on built-in function index:


index(...) method of builtins.list instance
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.


>>> #这是具体用例

--------------------------------------

书上说:python在分割文本上比C语言和Java语言都更具优势 = =

>>> mystring = "Monty Python ? And the holy Grail!\n"
>>> print(mystring.split())
['Monty', 'Python', '?', 'And', 'the', 'holy', 'Grail!']

>>>

所以说,默认的就是空格为分割点= =

---------------------------------------

要开始变形了= = split变strip

>>> mystring = "Monty Python ? And the holy Grail!\n"
>>> print(mystring.strip())
Monty Python ? And the holy Grail!

>>>#\n 不见了

--------------还提到了restrip(),lstrip() = =分布就是right ,left 去除尾部空白符 = =

>>> mystring = " Monty Python ? And the holy Grail!\n"#特意输入了一个空格

>>> print(mystring.lstrip())
Monty Python ? And the holy Grail!


>>> print(mystring.rstrip())
 Monty Python ? And the holy Grail! #这里有空格哦
>>>

---------------------------------------------

大写upper()

>>> print(mystring.upper())
MONTY PYTHON ? AND THE HOLY GRAIL!


>>>

-----------------------------------------

替换字符串 # replace()

 Monty Python ? And the holy Grail!
>>> print(mystring.replace('!',''''''))
 Monty Python ? And the holy Grail


>>>

问题为什么要这么多‘’‘’‘?

然后试了一下

>>> print(mystring.replace('!','''))
...
...

...

结果,这些事转移,怎么要六个这么多 = =

------------------------------------

下面是正则表达式 = = #匹配,索引,搜索,这些词都适合吧

-----------------------------------下面就是这这段话里面,搜索python这个词 = =,有的就输出一个句子

>>> mystring = " Monty Python ? And the holy Grail!\n"

>>> if re.search('Python',mystring):
...     print("We found python")
... else:#一定要冒号 ,然后这里对齐if的
...     print("no")
...
We found python

>>>


------------------------------------

>>> print(re.findall('o',mystring))
['o', 'o', 'o']

>>> # find 找到 all 所有的字符,在我的句子里面

-----------------------------------

字典  # 也被称之为 关联数组/存储

-----------------------------------

说明:只要几行代码,就能构建起来一个非常复杂的字典结构(不会是 abbaabcacb,乘法吧)

还是那句话 mystring = monty pyhon!and the holy grain

>>> word_freq = {}
>>> for tok in mystring.split():
...     if tok in word_freq:
...         word_freq [tok]+=1
...     else:
...         word_freq [tok]=1
...
>>> print(word_freq)
{'Monty': 1, 'Python': 1, '!': 2, 'And': 1, 'the': 1, 'holy': 1, 'Grain': 1}

>>>

-------------------------------------------------

编写函数

----------------------从def开始-------------------

-----------return结束-----------------------------

错误的地方

>>> import sys
>>> def wordfreq(mystring):
...     '''
...
...     Function to grnerated the frequency distributino of the given text
...     '''
...     print(mystring)
...     word_freq={}
...     for tok in mystring .split():
...           if tok in word_freq:
...                  word_freq [tok]+=1
...           else:
...                  word_freq [tok]=1
...     print(word_freq)
... def main():
  File "<stdin>", line 14
    def main():
      ^
SyntaxError: invalid syntax
>>> def main():
...     str="This is my fist python program"
...     wordfreq(str)
... if _name_ == '_main_':
  File "<stdin>", line 4
    if _name_ == '_main_':
     ^
SyntaxError: invalid syntax
>>> def main():
...     str="This is my fist python program"
...     wordfreq(str)
... if _name_ == '_main_':
  File "<stdin>", line 4
    if _name_ == '_main_':
     ^
SyntaxError: invalid syntax
>>> if _name_ == '_main_':
...    main()
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_name_' is not defined
>>>

-------------------------------

所有我要用文本编辑器来编写



结果,不知道终端是什么东西哦= =



最终解决了问题- -,然后就可以去吃饭了

E:\>python mywordfreq.py "this is logo"

This is my first python program
{'This': 1, 'is': 1, 'my': 1, 'first': 1, 'python': 1, 'program': 1}


E:\>

2018年3月7日11:47:06




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值