【问题标题】:How can i use split function in python to split parts of text and save them to a different file?如何在 python 中使用 split 函数来拆分部分文本并将它们保存到不同的文件中?
【发布时间】:2017-11-30 15:46:35
【问题描述】:

您好,我在 python 中使用 split 函数时遇到问题,但没有成功。我使用爬虫收集了一些推文,我需要将每条推文的某些部分拆分为不同的 .json 文件,特别是 ID 和 #(hashtag)。我一直在使用拆分功能但没有成功我做错了什么?我想将“id”和“text”之后的内容保存到不同的 .json 文件
文本如下所示:

{"created_at":"Fri Oct 20 16:35:36 +0000 2017","id":921414607302025216,"id_str":"921414607302025216","text":"@IdrisAhmed16 loooooool 谁说我在间接给你??

def on_data(self, data):
    try:
        #print data
        with open('Bologna_streams.json', 'r') as f:
            for line in f:

                tweet = data.spit(',"text":"')[1].split('",""source"')[0]
                print (tweet)

                saveThis = str(time.time()) + '::' +tweet

                saveFile = open('Bologna_text_preprocessing.json', 'w')
                json.dump(data)
                saveFile.write(saveThis)
                saveFile.write(tweet)
                saveFile.write('\n')
                saveFile.close()
                f.close()
        return True
    except BaseException as e:
        print("Error on_data: %s" % str(e))
        time.sleep(5)

def on_error(self, status):
    print (status)

【问题讨论】:

  • 你能举一个你试图分割的文本的例子
  • @NickChapman 的意思是:you 可以用您尝试拆分的文本示例更新您的 question 吗?
  • 当然。谢谢
  • 您在处理 json 文件时应该使用 json 模块。它不会直接解析 JSON 文本,而是会为您将其转换为 dict,然后您无需自己解析即可访问字段。
  • @c0lon 在编程方面,我实际上是一个菜鸟:p 你能帮我写一个例子来理解你的意思吗?谢谢

标签: python json function twitter split


【解决方案1】:

我认为您应该在命令行上以交互方式或在小脚本中尝试 Python。

考虑一下:

text="""
{"created_at":"Fri Oct 20 16:35:36 +0000 2017","id":921414607302025216,"id_str":"921414607302025216","text":"@IdrisAhmed16 learn #python"}
""".strip()

print(text.split(":"))

这将在控制台中打印:

['{"created_at"', '"Fri Oct 20 16', '35', '36 +0000 2017","id"', '921414607302025216,"id_str"', '"921414607302025216","text"', '"@IdrisAhmed16 learn #python"}']

或者,在新行上打印每个分屏:

print("splits:\n")
for item in text.split(":"):
  print(item)
print("\n---")

将打印这个:

splits:

{"created_at"
"Fri Oct 20 16
35
36 +0000 2017","id"
921414607302025216,"id_str"
"921414607302025216","text"
"@IdrisAhmed16 #learn python"}

---

换句话说,split 已经完成了它应该做的事情:找到每个 ":" 并围绕这些字符拆分字符串。

你要做的是解析 JSON:

import json

parsed = json.loads(text)
print("parsed:", parsed)

parsed 变量是一个普通的 Python 对象。结果:

parsed: {
  'created_at': 'Fri Oct 20 16:35:36 +0000 2017',
  'id': 921414607302025216,
  'id_str': '921414607302025216',
  'text': '@IdrisAhmed16 learn #python'
}

现在您可以对数据进行操作,包括检索 text 项目并将其拆分。

但是,如果目标是查找所有主题标签,则最好使用正则表达式:

import re
hashtag_pattern = re.compile('#(\w+)')
matches = hashtag_pattern.findall(parsed['text'])
print("All hashtags in tweet:", matches)

print("Another example:", hashtag_pattern.findall("ok #learn #python #stackoverflow!"))

结果:

All hashtags in tweet: ['python']
Another example: ['learn', 'python', 'stackoverflow']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多