如何在python中的字符串中查找大写字母

时间:2015-02-21 09:44:01

标签: python regex

我想在任何位置找到一个字符串中的大写字母,我希望如果一个字符串在一个字符串中的任何位置都包含大写字母,那么就要反对该字符串" 1"应该打印,如果字符串在任何位置都不包含任何大写字母,那么" 0"应该打印该字符串。为此我写了一个python代码,但它无法正常工作

file='C:/Python26/test.txt'
f=open('letters.txt','w')
pattern='[A-Z+]'
with open(file, 'r') as rf:

    for word in rf:
        for i in word.split():
            if word[0].isupper():               ## finding letters starting with uppercase letters
                  f.write(word.strip("\n")+"\t"'1'"\n");
            elif word.isupper():                ## finding string containing all capital letters
                  f.write(word.strip("\n")+"\t"'1'"\n");
            elif re.search(pattern, word):      ## finding string containing capital letter at any position 
                  f.write(word.strip("\n")+"\t"'1'"\n");
            else:
            f.write(word.strip("\n")+"\t"'0'"\n");
    f.close()

我的示例性数据就像这样
    SRC
    单克隆抗体
                                                                                                                                                                                                                32DC32
P50

激活
风扇

的NFκB
 IL23RE

但我的出局就像这样

Src 1
    mAB 1
                                                                                                                                                                                                                32DC32 1
P50 1
1 激活0
风扇0
0
      1
NFKappaB 1
IL23RE 0
猫0

哪会产生错误的结果。它没有迎合白色空间并给出了标题" 1"由于这个选举,期间(。)没有得到任何标签,而且#34; 0"也不是" 1"

1 个答案:

答案 0 :(得分:1)

只需使用re.search代替re.match,因为re.match会尝试从字符串的开头进行匹配。

import re
file='infile'
f=open('outfile','w')
pattern='[A-Z]'
with open(file, 'r') as rf:
    for word in rf:
        if re.search(pattern, word):
            f.write(word.strip() + " 1\n")
        else:
            f.write(word.strip() + " 0\n")
f.close()