我在Django中提交了一个表单,我写了一个干净的函数,试图通过TextField查看该字段中的任何单词是否与这样格式的单词匹配 - > #tweet,#people等等,但我似乎无法让它工作(表单保存精美顺便说一句),我的正则表达式知识大约为零,是的我知道我可以在这里使用模型表格但我喜欢尝试,因为我是Django的新手。
forms.py
class TweetForm(forms.Form):
tweets = forms.CharField(widget=forms.Textarea(), initial='Write your tweets here')
class Meta:
fields=('tweets',)
def clean(self):
data = self.cleaned_data
regular = re.compile('\b#\w\w+')
clean_tweets = data['tweets']
for lines in clean_tweets:
words = regular.findall(lines)
for hashtags in words:
print hashtags #want to print them in the terminal
def __init__(self, userprofile, *args, **kwargs):
super(TweetForm, self).__init__(*args, **kwargs)
self.userprofile = userprofile
def save(self, *args, **kwargs):
data=self.cleaned_data
obj = Tweet(tweets=data['tweets'], userprofile=self.userprofile, date=timezone.now(), )
obj.save()
答案 0 :(得分:0)
我最终弄明白了,这就是你可以做到的,我将数据转换成一个列表,然后用枚举器运行for循环。
forms.py
def clean(self):
data = self.cleaned_data
regex = re.compile("\B#\w\w+")
cleaned_tweets = data['tweets']
split_tweets = cleaned_tweets.split()
for i, x in enumerate(split_tweets):
if re.search(regex, x):
print i, x