处理FNLP coursework1 代码时发现:
1、 python和C/C++拷贝机制的不同
python中赋值时进行的拷贝是浅拷贝
要深拷贝需要:
import copy
orig_a=a #浅拷贝
orig_a=copy(a) #浅拷贝
orig_a=copy.deepcopy(a) #深拷贝
2、 isalpha()的用法:
如果前面不加上encode()方法,在判断非英语字符时会失误
string="这是汉字"
print(string.isaplha()) #True
print(string.encode().isaplha()) #False
3、FNLP部分源码
使用NLP库:NLTK(2.4.5)进行NLP任务,包括N-gram Model的调用,将corpora分解成句子/词语,计算交叉熵等
##NLTK 示例代码
from nltk_model import *
from nltk.corpus import brown
from nltk.probability import LidstoneProbDist
import copy
est = lambda fdist, bins: LidstoneProbDist(fdist, 0.2)
lm = NgramModel(3, brown.words(categories='news'), estimator=est)
print(lm)
print(lm._backoff)
print(lm.entropy(['The', 'Fulton', 'County', 'Grand', 'Jury', 'said',
'Friday', 'an', 'investigation', 'of', "Atlanta's", 'recent',
'primary', 'election', 'produced', '``', 'no', 'evidence',
"''", 'that', 'any', 'irregularities', 'took', 'place', '.']))
a = [['?', 'A', ':', 'RomanMack6s', 'http://formspring.me/RomanMack6s/q/90468625', 'Name', 'Q', ':', 'Whats', 'Your'],
['a', 'avisen', 'ccs', 'cuando', 'fino', '..', 'hoy', 'llegen', 'lo', 'paso', 'Por', 'q', 'que', '@user2075716'],
['@user10319815', ':', 'お疲れ様です', '。', 'ブログに掲載されたサルコジ大統領のスピーチ', '、', '心を揺り動かす', '、', '言葉では表現できないような力強さを感じました', '。',
'こんな素晴らしいメッセージに巡り会えて幸せです', '。', '有難うございました', '。', 'そんな風に言っていただけると嬉しいです', '。', 'RT']]
or_a=copy.deepcopy(a) #python的赋值本质是浅拷贝 深拷贝要用deepcopy方式
for s in a:
new_s = []
for w in s:
if w.isalpha():
new_s.append(w)
s = new_s
print(or_a==a) #这种for写法(不用下标访问)无法真实替换原先迭代对象里的元素!本质是深拷贝!
for i in range(len(a)):
new_s = []
for w in a[i]:
if w.encode().isalpha():
new_s.append(w)
a[i] = new_s
print(or_a==a)