如何在Python TXT文件中进一步拆分一条线?

发布于 2025-02-06 18:08:01 字数 673 浏览 2 评论 0 原文

我试图将一条线向下分成较小的元素,

每行都包含鸟类的名字及其已看到的次数。如果名称匹配,我正在尝试显示两者,但找不到进一步划分一行的方法。

这是我的代码:

with open("birdFile.txt", "w") as file:
numRecs = int(input("How many records do you wish to write? "))
for n in range(1,numRecs+1):
  birdName = input("Enter bird name: ")
  birdsReported = input("Enter number of bird reported: ")
  file.write(birdName + birdsReported + ",")

with open("birdFile.txt", "r") as file:
  birdNameSearch = input("What bird are you searching for? ")
  for line in file:
    file = line.split(",")
    birdName = line[0]
    birdsSeen = line[1]
    if birdNameSearch == birdName:
      print(birdName + ": " + birdsSeen)

I am trying to split a line down into smaller elements

Each line contains the birds' name and the number of times it has been seen. I am trying to display them both if the name matches but I can't find a way to split one line down further.

Here's my code:

with open("birdFile.txt", "w") as file:
numRecs = int(input("How many records do you wish to write? "))
for n in range(1,numRecs+1):
  birdName = input("Enter bird name: ")
  birdsReported = input("Enter number of bird reported: ")
  file.write(birdName + birdsReported + ",")

with open("birdFile.txt", "r") as file:
  birdNameSearch = input("What bird are you searching for? ")
  for line in file:
    file = line.split(",")
    birdName = line[0]
    birdsSeen = line[1]
    if birdNameSearch == birdName:
      print(birdName + ": " + birdsSeen)

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

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

发布评论

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

评论(1

只等公子 2025-02-13 18:08:01

您写了

  file.write(birdName + birdsReported + ",")

通知,逗号是在数字之后的 - 您想要它
之前,要将名称与数字分开。


另外,您需要在行结束时 \ n newline。
这是通过F-string最方便完成的:

  file.write(f'{birdName},{birdsReported}\n')

考虑使用CSV模块:

You wrote

  file.write(birdName + birdsReported + ",")

Notice that the , comma came after the number -- you want it
before, to separate name from number.


Also, you'll want a \n newline at end of line.
This is most conveniently accomplished with an f-string:

  file.write(f'{birdName},{birdsReported}\n')

Consider using the csv module: https://docs.python.org/3/library/csv.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文