我这样写不对,但我不知道哪里出了问题,所以在这个题目中要怎么计算目标字符串出现的个数啊?
filename = 'text.txt'
# 读取文本文件,获取目标字符串和文本内容
with open(filename, 'r') as f:
target_str = f.readline().strip() # 第一行为目标字符串
content = f.read().replace('\n', ' ') # 将换行符替换为空格
# 使用字符串的count()方法统计目标字符串在文本中出现的频次
freq = content.count(target_str)
# 输出统计结果
print(f'目标字符串“{target_str}”在文本文件中出现了{freq}次。')
# 定义函数,对目标文本文件进行遍历
def count_word(file_path, target_word):
count = 0
with open(file_path, 'r') as file:
for line in file:
count += line.count(target_word)
return count
# 输入目标文本文件路径和要查询的字符串
file_path = input("请输入目标文本文件路径:")
target_word = input("请输入要查询的字符串:")
# 调用函数统计目标字符串在目标文本文件中出现的次数
count = count_word(file_path, target_word)
# 输出结果
print("目标字符串在目标文本文件中出现的次数为:%d" % count)
使用该程序时,只需要在终端(或命令行)输入文件路径和要查询的字符串,程序将自动统计目标字符串在目标文本文件中出现的次数并输出结果。
我可以给出关于程序中目标字符串计数的解决方案,具体步骤如下:
import re
def count_target(t, text):
count = len(re.findall(t, text))
return count
完整代码如下:
import re
def count_target(t, text):
count = len(re.findall(t, text))
return count
text = "This is a test text for counting target string. The target string is 'target'."
target = "target"
print("The target string appears", count_target(target, text), "times in the text.")
输出结果为:The target string appears 2 times in the text.