簡體   English   中英

Python:使用.isalpha() 計算字數中的特定單詞/字符

[英]Python: Using .isalpha() to count specific words/characters in a word count

我創建了一個 function 可以計算文本文件中的特定單詞或字符。

但是我想創建一個條件,其中 function 只計算一個被字母包圍的字符。 例如在文本文件中。

'This test is an example, this text doesn't have any meaning. It is only an example.'

如果我要通過我的 function 運行此文本,測試撇號 (') 的計數,它將返回 3。但是我希望它返回 1,僅適用於 2 個字母字符內的撇號(例如不是或不會),但我希望它忽略沒有被字母包圍的所有其他撇號,例如單引號。

我嘗試使用 .isalpha() 方法,但語法有問題。

我認為正則表達式會更好,但如果你必須使用isalpha ,比如:

s = "'This test is an example, this text doesn't have any meaning. It is only an example.'"
sum(s[i-1].isalpha() and s[i]=="'" and s[i+1].isalpha() for i in range(1,len(s)-1))

返回 1。

如果您只想打折包含字符串本身的引號,最簡單的方法可能是在計數之前將它們從字符串中strip

>>> text = "'This test is an example, this text doesn't have any meaning. It is only an example.'"
>>> text.strip("'").count("'")
1

另一種方法是使用像\w'\w這樣的正則表達式,即字母,后跟' ,然后是字母:

>>> sum(1 for _ in re.finditer("\w'\w", text))
1

這也適用於字符串內的引號:

>>> text = "Text that has a 'quote' in it."
>>> sum(1 for _ in re.finditer("\w'\w", text))
0

但它也會錯過后面沒有另一個字母的撇號:

>>> text = "All the houses' windows were broken."
>>> sum(1 for _ in re.finditer("\w'\w", text))
0

正如 xnx 已經指出的,正確的方法是使用正則表達式:

import re

text = "'This test is an example, this text doesn't have any meaning. It is only an example.'"

print(len(re.findall("[a-zA-Z]'[a-zA-Z]", text)))
"""
Out:
    1
"""

這里模式中的撇號被一組英文字母包圍,但是有許多預定義的字符集,有關詳細信息,請參閱RE 文檔

你應該只使用正則表達式:

import re

text = "'This test is an example, this text doesn't have any meaning. It is only an example.'"

wordWrappedApos = re.compile(r"\w'\w")
found = re.findall(wordWrappedApos, text)
print(found)
print(len(found))

如果要確保其中沒有數字,請用“\w”替換“[A-Za-z]”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM