我有一个非常大的js React项目,我想搜索项目中的一些特定单词,但有2400个单词,所以我无法使用vsc的ctrl shift搜索我需要一个插件或程序,它需要2400个单词作为输入,然后搜索整个项目并告诉 x 这个词在这个项目中使用了 5 次。我尝试了这个程序,它不起作用
import os
def search_text_in_directory(directory, text_to_search):
total_occurrences = 0
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".js"):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
occurrences = content.count(text_to_search)
total_occurrences += occurrences
if occurrences > 0:
print(f"'{text_to_search}' found in '{file_path}'")
return total_occurrences
directory_to_search = r"C:\Users\hmmer\newsapi-app" # Your project directory path
text_to_search = "news-image"
total_occurrences = search_text_in_directory(directory_to_search, text_to_search)
print(f"Total occurrences of '{text_to_search}': {total_occurrences}")
我假设您的系统上存在最常见的 UNIX 工具:
cd directory_to_search
grep -oR text_to_search * | wc -l
^- 这将输出出现的次数。
您可以将
i
添加到 grep (-oRi
) 以进行不区分大小写的匹配。
grep: Searches for patterns etc.
-o: Prints only the matching part of the lines.
-R: Recursively search subdirectories listed. (i.e., force grep to behave as rgrep).
-i: Perform case insensitive matching. By default, grep is case sensitive.
wc: Counts words etc.
-l: The number of lines in each input file is written to the standard output.