如何根据python中的后缀提取单词
我有以下python代码:如何根据python中的后缀提取单词,python,nltk,Python,Nltk,我有以下python代码: import re; import nltk; from nltk.util import ngrams; file="C:/Python26/test.txt"; f=open("Suffix.txt",'w'); with open(file,'r') as rf: lines = rf.readlines(); c=0; for word in lines: if word.endswith(beta):
import re;
import nltk;
from nltk.util import ngrams;
file="C:/Python26/test.txt";
f=open("Suffix.txt",'w');
with open(file,'r') as rf:
lines = rf.readlines();
c=0;
for word in lines:
if word.endswith(beta):
f.write(word.strip("\n")+"\t"'1'"\n");
c=c+1;
else:
f.write(word.strip("\n")+"\t"'0'"\n");
c=c+1;
print c;
f.close()
这段代码没有给那些以“beta”开头的单词加上标记“1”,当我用statrswith()
替换endswith()
时,这段代码工作得很好,它给了以“beta”开头但不适用于endswith()
的带有标记“1”的单词
我不太了解这种行为。为什么会发生这种情况
我的文件看起来像这样
IL-2基因
表达式
和
NF-κ
B
激活
通过
CD28
需要
反应性
氧气
生产
通过
5-脂氧合酶
.这是因为
这个词以'\n'
结尾。您应该确保在检查之前去掉该部分,或者检查它是否以'beta\n'
结尾,然后重试
if word.strip().endswith(beta):
您是否尝试了word.rstrip().endswith(beta版)
?您也不需要将所有行读取到内存中,您可以迭代files对象,这是python而不是c删除
thx,运行良好,结果正确无需担心,您也不需要在脱衣舞中指定“\n”
,默认情况下会删除换行符,最后使用rstrip
从字符串末尾删除。您能给出suffix.txt
的一个片段吗?