如何计算随机字母包围的特定字符

时间:2019-05-17 13:36:16

标签: python regex python-3.x

我正在尝试使用字典来计算标点符号:撇号(')和连字符(-)。我想看看是否可以使用列表/字典/ for循环和布尔表达式来实现这一点。如果标点符号被其他字母包围,则必须予以计数!例如。千斤顶(即3个连字符),不应该(1个撇号)。这些字母可以是从a到z的任何字母。同样,由于这是分配的一部分,因此无法使用任何模块/库。我没有主意,不知道该怎么办。 任何帮助将不胜感激。

这是我尝试的方法:但是出现KeyError:0

def countpunc2():
filename = input("Name of file? ")
text = open(filename, "r").read()
text = text.lower()  #make all the words lowercase (for our convenience)
for ch in '!"#$%&()*+./:<=>?@[\\]^_`{|}~':
    text = text.replace(ch, ' ')
for ch in '--':
    text = text.replace(ch, ' ')
words = text.split('\n')       #splitting the text for words
wordlist = str(words)
count = {}                 #create dictionary; the keys/values are added on
punctuations = ",;'-"
letters = "abcdefghijklmnopqrstuvwxyz"
for i, char in enumerate(wordlist):
    if i < 1:
        continue
    if i > len(wordlist) - 2:
        continue
    if char in punctuations:
        if char not in count:
            count[char] = 0
        if count[i-1] in letters and count[i+1] in letters:
            count[char] += 1
print(count)

更新: 我将代码更改为:

def countpunc2():
filename = input("Name of file? ")
text = open(filename, "r").read()
text = text.lower()  #make all the words lowercase (for our convenience)
for ch in '!"#$%&()*+./:<=>?@[\\]^_`{|}~':
    text = text.replace(ch, ' ')
for ch in '--':
    text = text.replace(ch, ' ')
words = text.split('\n')       #splitting the text for words
wordlist = str(words)
count = {}                 #create dictionary; the keys/values are added on
punctuations = ",;'-"
letters = "abcdefghijklmnopqrstuvwxyz"
for i, char in enumerate(wordlist):
    if i < 1:
        continue
    if i > len(wordlist) - 2:
        continue
    if char in punctuations:
        if char not in count:
            count[char] = 0
        if wordlist[i-1] in letters and wordlist[i+1] in letters:
            count[char] += 1
print(count)

虽然它给我输出的结果是不正确的。 样本文件:https://www.dropbox.com/s/kqwvudflxnmldqr/sample1.txt?dl=0 预期结果必须为:{',':27,'-':10,';' :5,“'”:1}

3 个答案:

答案 0 :(得分:0)

您可以将输入字符串的字符映射为3类:字母(a),标点(p)和空格。然后将它们分成三组(3个字符的序列)。从这些中分离出a-p-a三元组并计算不同的标点符号的数量。

例如:

string="""jack-in-a-box (that is 3 hyphens) and shouldn't (1 apostrophe)."""

categ   = [ "pa"[c.isalpha()] if c != " " else "s" for c in string ]
triples = [ triple for triple   in zip(categ,categ[1:],categ[2:]) ]
pChars  = [ p      for p,triple in zip(s[1:],triples) if triple==("a","p","a") ]
result  = { p:pChars.count(p) for p in set(pChars) }

print(result) # {"'": 1, '-': 3}

如果不允许使用isAlpha()zip(),则可以使用in运算符和for循环来编写等效代码。

答案 1 :(得分:0)

下面是一个以非常清楚的方式说明它的示例:

end_cap_characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
special_characters = [";", ":", "'", "-", ","]

def count_special_characters(in_string):
    result = {}
    for i in range(1, len(in_string) - 1):
        if in_string[i - 1] in end_cap_characters:
            if in_string[i + 1] in end_cap_characters:
                if in_string[i] in special_characters:
                    if in_string[i] not in result:
                        result[in_string[i]] = 1
                    else:
                        result[in_string[i]] +=1
    return result

print(count_special_characters("jack-in-the-box"))
print(count_special_characters("shouldn't"))
print(count_special_characters("jack-in-the-box, shouldn't and a comma that works,is that one"))

输出:

{'-': 3}
{"'": 1}
{'-': 3, "'": 1, ',': 1}

很明显,这可以简化,但是我将其留给您练习;)。

更新

根据您编辑的问题和发布的代码,您需要更新以下行:

if count[i-1] in letters and count[i+1] in letters:

收件人:

if wordlist[i-1] in letters and wordlist[i+1] in letters:

答案 2 :(得分:0)

我可能会简化它。

#!/usr/bin/env python3
sample = "I'd rather take a day off, it's hard work sitting down and writing a code. It's amazin' how some people find this so easy. Bunch of know-it-alls."

punc = "!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~" 
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

d = {}
for i, char in enumerate(sample):
    if i < 1:
        continue

    if i > len(sample) - 2:
        continue

    if char in punc:
        if char not in d:
            d[char] = 0

        if sample[i - 1] in letters and sample[i + 1] in letters:
            d[char] += 1

print(d)

输出:

{"'": 3, ',': 0, '.': 0, '-': 2}

Dunno,您将获得“;”从。另外,您的逗号旁边还有一个空格..因此,它不在此处计数..如果该计数有效,请在字母变量中添加一个空格。

正在发生的事情的解释:

我们启动一个字典,并以sample的形式读取示例文本,并使用enumerate逐个字符地对其进行迭代,以处理索引。如果距离终点太近或无法开始排位赛,我们将其跳过。

我使用枚举中的i变量检查字符之前和之后的字符。并加上合格的计数。

注意:尽管有爆炸性,但此代码在python2中有效