Win2D
答案 0 :(得分:0)
您可能希望将文件拆分为撇号,空格以及任何其他标点符号。要在多个分隔符处拆分,您需要import re
并使用正则表达式。
如果您还希望匹配不同案例的字词(例如“您和您”),则需要使用lower()
。
import re # use regular expressions
def paraula(file,palabrabuscar):
abrirLetra = open(file) #Open the file
palabras = ""
vegades = 0
for palabras in re.split(r'[\s\'\"\.,;]+', abrirLetra.read()):
# split at every: \s whitespace
# \' apostrophe
# \" quotation mark
# \. full stop
# , comma
# ; semi-colon
#
# The plus sign at the end splits at one or more delimiters in
# a row (for example "Hello. Hi." has a full stop and a space
# together between Hello and Hi).
#
# Backslashes are added before special characters
# (for example s matches the letter s, but \s matches whitespace).
if (palabras.lower() == palabrabuscar.lower()): #Look for coincidence
# Convert both to lowercase if you want to match
# you, You and YOU.
vegades = vegades +1
abrirLetra.close()
return vegades
file = 'lletra.txt'
print paraula(file,"you")