Python - 在线搜索单词、计算它、添加它

发布于 2024-12-15 11:41:38 字数 194 浏览 0 评论 0原文

我很确定我想得太多了,而且有一个简单的结果,但我似乎无法将它们放在一起。

我正在寻找一种搜索方法。我想要一个 Python 脚本在文本文件中搜索关键字并计算它出现的行数。尽管如果关键字在一行中多次出现,我仍然想只计算一次。

长话短说;如果键盘出现在一行上,我希望它计算该行并将其添加到数学方程中。

非常感谢任何帮助!提前致谢。

I'm pretty sure I'm over thinking this and there's a simple outcome for it, but I just can't seem to put it all together.

I'm looking for a kind of a search method. I'd like a Python script search a text file for a keyword and count how many lines it appears on. Though if the keyword comes up on a single line multiple times, I'd like to still only count it once.

Long story short; If a keyboard comes up on a single line, I want it to count that line and add it to what will be a math equation.

Any help is greatly appreciated! Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

┾廆蒐ゝ 2024-12-22 11:41:38

您可以定义以下函数。

def lcount(keyword, fname):
    with open(fname, 'r') as fin:
        return sum([1 for line in fin if keyword in line])

现在,如果您想知道“foo.cpp”中包含“int”的行数,您可以:

print lcount('int', 'foo.cpp')

您可以在命令行上执行的另一种选择(如果您在适当的平台上)是:

grep int foo.cpp | wc -l

You can define the following function.

def lcount(keyword, fname):
    with open(fname, 'r') as fin:
        return sum([1 for line in fin if keyword in line])

Now if you want to know the number of lines containing "int" in "foo.cpp", you do:

print lcount('int', 'foo.cpp')

An alternative that you can do on the command line (if you are on an appropriate platform) is:

grep int foo.cpp | wc -l
身边 2024-12-22 11:41:38

非 Python Unix 解决方案相当直接:

  • “在文本文件中搜索关键字”是一个 grep
  • “计算有多少行”是一个 wc

您实现起来有困难吗Python 中这两者的本质是什么?

A non-Python Unix solution is fairly immediate:

  • "search a text file for a keyword" is a grep
  • "count how many lines" is a wc

Do you have difficulty implementing the essence of either of these in Python?

我不在是我 2024-12-22 11:41:38

假设f是文件对象,

lines = f.readlines()
print len([line for line in lines if keyword in line])

Assuming f is the file object,

lines = f.readlines()
print len([line for line in lines if keyword in line])
锦上情书 2024-12-22 11:41:38

也许你可以尝试这个:

def kwdCount(textContent, keyword):
    lines=textContent.split("\n")
    count=len([1 for line in lines if line.find(keyword)!=-1])
    return count

>>> yourTextFile="hello world\n some words here\n goodbye world"
>>> kwdCount(ourTextFile,"world")
    2

Perhaps you could try this:

def kwdCount(textContent, keyword):
    lines=textContent.split("\n")
    count=len([1 for line in lines if line.find(keyword)!=-1])
    return count

>>> yourTextFile="hello world\n some words here\n goodbye world"
>>> kwdCount(ourTextFile,"world")
    2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文